JavaScript中的拖拽事件

时间:2020-04-14
本文章向大家介绍JavaScript中的拖拽事件,主要包括JavaScript中的拖拽事件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!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>

原文地址:https://www.cnblogs.com/TomHe789/p/12695904.html