原生JS实现拖拽缩放元素

2020-11-26 15:22:05 浏览数 (1)

今天给大家分享一个用原生JS实现的拖拽缩放元素大小的Demo,效果如下:

以下是代码实现,欢迎大家复制粘贴及吐槽。

代码语言:javascript复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现拖拽缩放元素</title>
    <style>
        #div1 {

            width: 11px;
            height: 11px;
            background-color: #000;
            position: absolute;
            bottom: 0;
            right: 0;
            cursor: nw-resize;
        }

        #div2 {
            width: 200px;
            height: 150px;
            background: #CCC;
            position: relative;
        }
    </style>
    <script>
        window.onload = function () {

            var oDiv = document.getElementById('div1');
            var oDiv2 = document.getElementById('div2');

            oDiv.onmousedown = function (ev) {

                var oEvent = ev || event;

                var disX = oEvent.clientX - oDiv.offsetLeft;
                var disY = oEvent.clientY - oDiv.offsetTop;

                document.onmousemove = function (ev) {

                    var oEvent = ev || event;
                    //要加上子DIV的大小(oDiv.offsetWidth与oDiv.offsetHeight)
                    oDiv2.style.width = oEvent.clientX - disX   oDiv.offsetWidth   'px';
                    oDiv2.style.height = oEvent.clientY - disY   oDiv.offsetHeight   'px';
                };

                document.onmouseup = function () {

                    document.onmousemove = null;
                    document.onmouseup = null;
                };
            };
        };
    </script>
</head>

<body>
    <div id="div2">
        <div id="div1"></div>
    </div>
</body>

</html>

0 人点赞