面向对象实现拖拽案例

面向对象实现拖拽案例

QQ录屏20210317210736

<!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>
</head>
<body>
    <div class="box"></div>
    <div class="box1"></div>
</body>
</html>
 .box {
    
    
            width: 100px;
            height: 100px;
            position: absolute;
            left: 0px;
            top: 0px;
            cursor: move;
            background: pink;
        }
        .box1 {
    
    
            width: 100px;
            height: 100px;
            background: green;
            position: absolute;
            top: 100px;
            left: 0px;
            cursor: move;
        }

function Drag(ele){
    
    
            this.ele=ele;
            this.left=this.ele.offSetLeft;
            this.top=this.ele.offSetTop;
            this.init();//初始化函数调用
        }

        Drag.prototype.init = function(){
    
    
            this.ele.onmousedown=() =>{
    
    
                //console.log(this);
                this.move();
            };
            document.onmouseup = function(){
    
    
                document.onmousemove=null;
            };
        };
        Drag.prototype.move=function(){
    
    
            document.onmousemove = () =>{
    
    
                let e=window.event;
                this.left=e.clientX - this.ele.offsetWidth/ 2;
                this.top=e.clientY - this.ele.offsetHeight / 2 ;
                this.ele.style.left=this.left + "px";
                this.ele.style.top=this.top + "px";
            };
        };
        let box=document.querySelector(".box");

        new Drag(box);

创建对象

​ 描述对象

​ 静态属性

​ ele:拖拽的对象(dom元素)

​ left:移动的left

​ top:移动的top值

​ 动态方法

​ init() 初始化,获取元素 绑定事件

​ move()

​ 使用对象*

Drag.prototype.init = function(){
    
    
            this.ele.onmousedown=() =>{
    
    
                console.log(this);
                this.move();
            };

console.log(this);//控制台查看

在这里插入图片描述
这个函数事件调用函数 ,this指向事件驱动事件(即绑定事件的这个元素Drag),无法调用函数move(),前文说过了箭头函数,箭头函数的this和调用函数方法没有关系,这样可以跳出使用函数。

  • ​ 获取元素的尺寸:
  1. ​ clientWidth : 元素的width +左右的padding值
  2. ​ clientHeight :元素的height +上下padding值
  3. ​ clientLeft : 获取的元素的左边框
  4. ​ clientTop: 获取元素的上边框
  5. ​ offsetWidth :获取元素的width +左右的padding +左右的border
  6. ​ offsetHeight:获取元素的height + 上下padding +上下的border
  7. ​ offsetLeft:获取元素的左边的偏移量,如果元素 没有定位的时候 获 取的值 是这个元素 距离浏览器最左边的距离
  8. ​ offsetTop:获取元素上边的偏移量,如果没有定位的时候获取的是元素 距离浏览器最上面的距离
  • 当元素有定位的时候 ,并且父元素也有定位的时候,偏移量 为 这个元素的left 和 top值
  • ​ clientX 返回当事件被触发时,鼠标指针的水平坐标。
  • ​ clientY 返回当事件被触发时,鼠标指针的垂直坐标。

猜你喜欢

转载自blog.csdn.net/qq_43677817/article/details/114948938