移动拖拽特效

效果显示

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            /* 需要加上定位元素 */
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        // 获取div元素
        var oDiv = document.getElementsByTagName('div')[0];
        
        // 鼠标点击事件
        oDiv.onmousedown = function (e) {
            // 点击处到浏览器左上角的位置
            var startX = e.clientX;
            var startY = e.clientY;
            
            // div 到定位父级的位置
            var startLeft = oDiv.offsetLeft;
            var startTop = oDiv.offsetTop;
            
            // 鼠标移动事件
            document.onmousemove = function (ev) {
                // 设置移动后的样式
                // 
                oDiv.style.left = startLeft + ev.clientX - startX + 'px';
                oDiv.style.top = startTop + ev.clientY - startY + 'px';

                // 抬起鼠标清除样式
                document.onmouseup = function (ev1) {
                    document.onmouseup = null;
                    document.onmousemove = null;
                    document.onmousedown = null;
                };
                
                // 清除默认样式
                return false
            }
        }
    </script>
</body>
</html>
发布了288 篇原创文章 · 获赞 50 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/gklcsdn/article/details/104082113