實現div可以調整高度(div實現resize)


實現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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM