实现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, height: height}, { 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

原文地址:https://www.cnblogs.com/BillyYoung/p/11209041.html