欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用javascript(自定义事件)记录尺寸可变元素的尺寸变化过程

程序员文章站 2022-08-11 15:38:14
1.效果图 2.源码 ......

1.效果图

利用javascript(自定义事件)记录尺寸可变元素的尺寸变化过程

2.源码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <style type="text/css">
        div{
            border:1px solid black;
            width:200px;
            height: 95px;
            resize:both;
            overflow: auto;
        }
    </style>
    <script type="text/javascript">
        function showSize(elementSize) {
            console.log("width:"+elementSize.width+";height:"+elementSize.height);
        }
        HTMLDivElement.prototype.onsizechange = function (handleFunction) {
            var element = this;
            var lastWidth = element.clientWidth;
            var lastHeight = element.clientHeight;

            setInterval(function () {
                if (lastWidth === element.clientWidth && lastHeight === element.clientHeight)
                    return;
                if (typeof (handleFunction) == 'function') {
                    lastWidth = element.clientWidth;
                    lastHeight = element.clientHeight;
                    handleFunction({ width: lastWidth, height: lastHeight });

                }
            }, 100);
            return element;
        };
        window.onload = function () {
            var myDiv = document.getElementById("myDiv");
            myDiv.onsizechange(showSize);
        };
    </script>
</head>
<body>
<div id="myDiv"><p>尺寸可变元素<br/>width:200px;height:95px</p></div>
</body>
</html>