實現div可以調整高度(div實現resize)
一、div 實現resize(類似textarea)
代碼如下:
<!DOCTYPE html> <html><head><title>div實現textarea效果</title><style>#textarea {height: 200px;width: 300px;padding: 4px;border: 1px solid #888;resize: vertical;overflow: auto;}#textarea:empty:before {content: attr(placeholder);color: #bbb;}</style></head><body><div id="textarea" contenteditable="true" placeholder="請輸入內容..."></div></body> </html>
?
二、監聽div的resize事件
<!DOCTYPE html> <html><head><title>div監聽resize事件</title><style>.container {position: relative;width: 500px;height: 300px;background-color: black;padding: 4px;resize: vertical;overflow: auto;}.size-watch {width: 100%;height: 100%;position: absolute;visibility:hidden;margin: 0;padding: 0;border: 0;}</style> </head><body ><div class="container" id="mapDiv" >hello</div><script>function riseze (el, cb) {// 創建iframe標簽,設置樣式并插入到被監聽元素中var iframe = document.createElement('iframe');iframe.setAttribute('class', 'size-watch');el.appendChild(iframe);// 記錄元素當前寬高var oldWidth = el.offsetWidth;var oldHeight = el.offsetHeight;// iframe 大小變化時的回調函數function sizeChange () {// 記錄元素變化后的寬高var width = el.offsetWidth;var height = el.offsetHeight;// 不一致時觸發回調函數 cb,并更新元素當前寬高if (width !== oldWidth || height !== oldHeight) {cb({width: width, height: height}, {width: oldWidth, height: oldHeight});oldWidth = width;oldHeight = height;}}// 設置定時器用于節流var timer = 0;// 將 sizeChange 函數掛載到 iframe 的resize回調中 iframe.contentWindow.onresize = function () {clearTimeout(timer);timer = setTimeout(sizeChange, 20);};}//var el = document.getElementById("mapDiv");var el = document.querySelector('.container');riseze(el, (val, oldVal) => {console.log(`size changed!new: ${JSON.stringify(val)}, old: ${JSON.stringify(oldVal)}`);});</script></body> </html>
?
參考網站:
1、https://blog.csdn.net/liya_nan/article/details/81742370
2、https://segmentfault.com/a/1190000016550156