拖拽功能

发布时间 2023-04-09 19:49:49作者: 爱前端的小魏
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wsx{
            width: 500px;
            height: 400px;
            background-color: red;
            position: absolute;
            left: 0px;
            top: 0px;
        }
    </style>
</head>
<body>
    <div class="wsx">
    </div>

    <script>
        //鼠标按下后,盒子进行移动,抬起后,不在移动
        //思路分解
        //1.获取元素,鼠标点击后显示,鼠标抬起/移出不在移动(onmousedown,onmousemove,onmouseup)
        var wsx = document.querySelector('.wsx')
        //鼠标按下
        wsx.onmousedown = function(e){
        //求出鼠标按下的x和y
        var x = e.clientX;
        var y = e.clientY;
       
        //计算视口到盒子的距离
        var w = wsx.getBoundingClientRect()
        var w1 = w.left
        var w2 = w.top

                //获取视口元素宽度和高度
                //document.documentElement.clientWidth  浏览器窗口的宽度/高度
                var zw = document.documentElement.clientWidth
                var zh = document.documentElement.clientHeight
                //offsetWidth =自身宽度/高度
                var ew = wsx.offsetWidth
                var eh = wsx.offsetHeight
                //算出最大的视口
                var w3 = zw - ew
                var w4 = zh - eh
            //鼠标移入
            wsx.onmousemove = function(e){
                var x1 = e.clientX - x
                var y2 = e.clientY - y

                var left  = w1 + x1
                var top = w2 + y2
                //超出视频宽度和高度则走下面逻辑
                if(left < 0 ){
                    left = 0
                }
                if(left > w3){
                    left = w3
                }
                if(top < 0){
                    top = 0;

                }
                if(top > w4){
                    top = w4
                }


                wsx.style.left = left + 'px'
                wsx.style.top = top + 'px'
            }
            //鼠标移出,抬起
            wsx.onmouseup = function(){
                //移出后,停止移入事件
                wsx.onmousemove = null
            }
        }

    </script>
</body>
</html>