鼠标拖动效果js

<!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>Document</title>
    <style>
        .box {width: 100px;height: 100px;background: #ccc;position: absolute;left: 0;top: 0;}
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    var obox = document.querySelector(".box");
    //取到事件源的实际宽高
    var h = obox.offsetHeight;
    var w = obox.offsetWidth;
    // 取到可视页面的宽高
    var clientHeight = document.documentElement.clientHeight;
    var clientWidth = document.documentElement.clientWidth;
    obox.onmousedown = function(eve){
        // 鼠标点击时的解决兼容问题
        var e1 = eve || window.event;
        
        document.onmousemove = function(eve){
            // 鼠标滑动时解决兼容
            var e = eve || window.event;

            var t = e.clientY - e1.offsetY;
            var l = e.clientX- e1.offsetX ;
            // 通过判断div移动是否超出可视页面
            if(t<0){
                t=0;
            }
            if(l<0){
                l=0;
            }
            if(t>clientHeight-h){
                t = clientHeight-h;
            }
            if(l>clientWidth-w){
                l=clientWidth-w
            }
            // 给div设置移动的位置
            obox.style.top = t +"px";
            obox.style.left = l +"px";
        }
        // 鼠标相对于网页抬起时删除移动时间
        document.onmouseup = function(){
            document.onmousemove = null;
        } 
        
        
    }
    

</script>
</html>

在这里插入图片描述

发布了11 篇原创文章 · 获赞 12 · 访问量 471

猜你喜欢

转载自blog.csdn.net/weixin_45481771/article/details/100188161
今日推荐