欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript中的拖拽事件

程序员文章站 2022-05-05 22:06:25
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖拽</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: brown;
            position: absolute;
        }
        #box1{
            width: 100px;
            height: 100px;
            position: absolute;
            left: 200px;
            background-color:skyblue;
        }
        img{
            width: 100px;
            height: 100px;
            position: absolute;
            left: 400px;
        }
    </style>
    <script>
        window.onload = function () {
            var box = document.querySelector("#box");
            var box1 = document.querySelector("#box1");
            var img = document.querySelector("#img");
            drag(box);
            drag(box1);
            drag(img);
            // 将拖拽功能封装成了一个函数
            function drag(obj) {
                obj.onmousedown = function (event) {
                    // 兼容IE8 调用IE特有的方法setCapture()
                    obj.setCapture && obj.setCapture();
                    event = event || window.event;
                    // 得到盒子和鼠标之间的相对位移
                    var ol = event.clientX - obj.offsetLeft;
                    var ot = event.clientY - obj.offsetTop;

                    document.onmousemove = function (event) {
                        event = event || window.event;
                        // 更改盒子的偏移量, 并减去盒子和鼠标的相对位移
                        obj.style.left = event.clientX - ol + "px";
                        obj.style.top = event.clientY - ot + "px";
                        // 兼容IE8 调用IE特有的方法releaseCapture()
                        obj.releaseCapture && obj.releaseCapture();
                    };

                    document.onmouseup = function () {

                        // 结束事件onmousemove  onmouseup
                        document.onmousemove = null;
                        document.onmouseup = null;
                    };
                    return false;
                };
            }
        };

    </script>
</head>
<body>
<div id="box"></div>
<div id="box1"></div>
<img src="../../images/headPortrait.jpg" id="img">
</body>
</html>

JavaScript中的拖拽事件