首页 > 其他 > 详细

实现div可以调整高度(div实现resize)

时间:2019-07-18 19:27:26      阅读:102      评论:0      收藏:0      [点我收藏+]

实现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

实现div可以调整高度(div实现resize)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!