美文网首页
简单盒子拖拽,解决移动太快,脱离盒子

简单盒子拖拽,解决移动太快,脱离盒子

作者: 小柠有点萌 | 来源:发表于2020-08-04 14:05 被阅读0次
image.png
image.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{position:absolute;top:0;left:0; background:red;width:200px;height:200px;}

    </style>
</head>
<body>
    <div class="box"></div>
    <script>
        let box=document.querySelector(".box");
        box.addEventListener("mousedown",down)
        function down(e) {
            this.startL=this.offsetLeft;
            this.startT=this.offsetTop; //距离父级参照物的偏移
            this.startX=e.clientX;
            this.startY=e.clientY;
            // 解决鼠标移动拖动过快,焦点丢失。用bind。 
            //move.bind()会返回有个代理函数,所以绑定给事件的是一个代理函数,以后移除的也应该是代理函数才可以
            this._move = move.bind(this)
            this._up = up.bind(this)
            // this.addEventListener("mousemove",this._move);//移动太快,脱离盒子,所以给document添加二级document事件
            document.addEventListener("mousemove",this._move);
            document.addEventListener("mouseup",this._up);
        }
        function move(e) {
               console.log(e) 
               let curL=e.clientX-this.startX+this.startL;
               let curT=e.clientY-this.startY+this.startT;
               this.style.left=curL+"px";
               this.style.top=curT+"px";
            //    this.style.cssText=`left:${curL}px,top:${curT}px`
        }
        function up(e) {
            document.removeEventListener("mousemove",this._move);
            document.removeEventListener("mouseup",this._up);
            
            
        }

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

相关文章

网友评论

      本文标题:简单盒子拖拽,解决移动太快,脱离盒子

      本文链接:https://www.haomeiwen.com/subject/uwnrqktx.html