JS 拖拽功能实现

引自:https://blog.csdn.net/xiaoba_598/article/details/80503262

盒子拖拽—运用到的有onmousedown事件,onmousemove事件以及onmouseup事件

    1、当鼠标点击下去的时候我们需要获取鼠标所在位置的横纵坐标,然后获取盒子的离页面的横纵方向的距离
    2、计算出鼠标相对盒子的距离
    3、当鼠标移动的时候,获取鼠标移动的距离,在永鼠标此刻的位置减去鼠标相对盒子的距离,获得的是盒子此刻的坐标位置
    4、将这个位置赋值给盒子
    5、鼠标抬起,清除鼠标移动事件;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>鼠标拖拽</title>
    <style>
        .box{
            background-color: pink;
            width:200px;
            height:200px;
            border-radius: 50%;
            position: absolute;
            top:20px;
            left:100px;
        }
    </style>
</head>
<body>
    <div class="box">

    </div>
    <script>
        window.onload = function(){
            var box = document.getElementsByClassName('box')[0];
            function drag (ele){
                ele.onmousedown = function(e){
                    var e = e || window.event;  
                    //此处是为了兼容IE,因为IE中事件对象是作为全局对象( window.event )存在的;
                    var pageX = e.pageX || e.clientX + document.documentElement.scrollLeft;
                    var pageY = e.pageY || e.clientY + document.documentElement.scrollTop;
                    //获取鼠标相对盒子的位置;
                    var boxX = pageX - box.offsetLeft;
                    var boxY = pageY - box.offsetTop;
                    document.onmousemove = function(e){
                        var e = e || window.event;
                        var pageX = e.pageX || e.clientX + document.documentElement.scrollLeft;
                        var pageY = e.pageY || e.clientY + document.documentElement.scrollTop;
                      //将鼠标当前的坐标值减去鼠标相对盒子的位置,得到盒子当时的位置并将其赋值给盒子,实现移动效果
                        box.style.left = pageX - boxX +'px';
                        box.style.top = pageY - boxY + 'px';
                    }
                };
                document.onmouseup = function () {
                    //清除盒子的移动事件;
                    document.onmousemove = null;
                };
            } ;
            drag(box)
        }
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xiaoyuchen/p/JS.html