美文网首页
JS示例37-鼠标拖拽

JS示例37-鼠标拖拽

作者: 微小码 | 来源:发表于2019-04-06 20:30 被阅读0次
    <!DOCTYPE HTML>
    <html>
    
    <head>
        <meta charset="utf-8">
        <title>无标题文档</title>
        <style>
            #div1 {
                width: 200px;
                height: 200px;
                background: red;
                position: absolute;
            }
        </style>
        <script>
            window.onload = function () {
                var oDiv = document.getElementById('div1');
    
                var disX = 0;
                var disY = 0;
    
                oDiv.onmousedown = function (ev) { // 鼠标按下
                    var oEvent = ev || event;
    
                    disX = oEvent.clientX - oDiv.offsetLeft; // 横向距离 = 鼠标位置 - div位置
                    disY = oEvent.clientY - oDiv.offsetTop;
    
                    document.onmousemove = function (ev) { // 鼠标移动(事件加到document)
                        var oEvent = ev || event;
    
                        oDiv.style.left = oEvent.clientX - disX + 'px';
                        oDiv.style.top = oEvent.clientY - disY + 'px';
                    };
    
                    document.onmouseup = function () { // 鼠标抬起(事件加到document)
                        document.onmousemove = null; // 关闭移动事件
                        document.onmouseup = null; // 关闭抬起事件
                    };
                };
            };
        </script>
    </head>
    
    <body>
        <div id="div1"></div>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:JS示例37-鼠标拖拽

          本文链接:https://www.haomeiwen.com/subject/kjrdiqtx.html