原生JS實現拖拽位置預覽

本文給大傢分享一個拖拽元素時添加預覽的小Demo,效果如下:

以下是代碼實現,歡迎大傢復制粘貼及吐槽。

<!DOCTYPE html>
<html>
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS實現拖拽位置預覽</title>
    <style>
        .box {
            position: absolute;
            border: 1px dashed black;
        }
 
        #div1 {
            width: 100px;
            height: 100px;
            background: yellow;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function () {
 
            var oDiv = document.getElementById('div1');
 
            oDiv.onmousedown = function (ev) {
 
                var oEvent = ev || event;
                var disX = oEvent.clientX - oDiv.offsetLeft;
                var disY = oEvent.clientY - oDiv.offsetTop;
 
                //創建一個虛線框的div
                var oNewDiv = document.createElement('div');
 
                oNewDiv.className = 'box';
                //減去邊框的大小與原div大小重合
                oNewDiv.style.width = oDiv.offsetWidth - 2 + 'px';
                oNewDiv.style.height = oDiv.offsetHeight - 2 + 'px';
                oNewDiv.style.left = oDiv.offsetLeft + 'px';
                oNewDiv.style.top = oDiv.offsetTop + 'px';
 
                document.body.appendChild(oNewDiv);
 
                document.onmousemove = function (ev) {
 
                    var oEvent = ev || event;
 
                    oNewDiv.style.left = oEvent.clientX - disX + 'px';
                    oNewDiv.style.top = oEvent.clientY - disY + 'px';
                };
 
                document.onmouseup = function () {
 
                    document.onmousemove = null;
                    document.onmouseup = null;
 
                    oDiv.style.left = oNewDiv.style.left;
                    oDiv.style.top = oNewDiv.style.top;
                    //移除虛線框
                    document.body.removeChild(oNewDiv);
                };
            };
        };
    </script>
</head>
 
<body>
    <div id="div1"></div>
</body>
 
</html>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: