JS拖拽目标

来源:互联网 发布:sql server 系统时间 编辑:程序博客网 时间:2024/05/22 10:40
<!DOCTYPE>
<html>

<head>
    <meta charset="utf-8">
    <style type="text/css">
        body {
            padding0;
            margin0;
        }
        
        #box {
            width200px;
            height200px;
            background-color#ccc;
            positionabsolute;
            cursorpointer;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            var box = document.getElementById("box");
            box.onmousedown = function (e) {
                var e = e || window.event;
                console.log(e.clientX);
                var diffX = e.clientX - box.offsetLeft;//鼠标相对目标偏移量X
                var diffY = e.clientY - box.offsetTop;//鼠标相对目标偏移量Y
                document.onmousemove = function (e) {
                    var e = e || window.event;
                    box.style.left = e.clientX - diffX + "px";
                    box.style.top = e.clientY - diffY + "px";
                };
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmousedown = null;
                };
            };

        };

    </script>
</head>

<body>
    <div id="box"></div>
</body>

</html>
0 0
原创粉丝点击