js简单实现拖拽功能

html:

<div class="mydiv1"></div>

css:

.mydiv1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
}

js:

let mydiv1 = document.querySelector(".mydiv1");
mydiv1.onmousedown = e => {
    let ev = e || window.event;
    let x = ev.clientX - mydiv1.offsetLeft;
    let y = ev.clientY - mydiv1.offsetTop;
    mydiv1.onmousemove = e => {
        let ev = e || window.event;
        let xx = ev.clientX;
        let yy = ev.clientY;
        mydiv1.style.left = xx - x + "px";
        mydiv1.style.top = yy - y + "px";
    }
    mydiv1.onmouseup = function () {
        mydiv1.onmousemove = "";
    }
}

好像没什么毛病,基本功能是实现了。传统的面向过程编程,代码没有什么拓展性,就是一步一步的实现,

同样这个案例,下面用面向对象的方法实现以下:

function Drag(ele) {
    this.ele = ele;
    this.downFn();
}
Drag.prototype.downFn = function () {
    this.ele.onmousedown = e => {
        let ev = e || window.event;
        let x = ev.clientX - this.ele.offsetLeft;
        let y = ev.clientY - this.ele.offsetTop;
        this.moveFn(x, y);
        this.upFn();
    }
}
Drag.prototype.moveFn = function (x, y) {
    this.ele.onmousemove = e => {
        let ev = e || window.event;
        let xx = ev.clientX;
        let yy = ev.clientY;
        this.setStyle(xx - x, yy - y)
    }
}
Drag.prototype.upFn = function () {
    this.ele.onmouseup = () => {
        this.ele.onmousemove = "";
    }
}
Drag.prototype.setStyle = function (leftNum, topNum) {
    this.ele.style.left = leftNum + "px";
    this.ele.style.top = topNum + "px";
}
let mydiv1 = document.querySelector(".mydiv1");
let drag1 = new Drag(mydiv1);

这么一看的话,好像更加复杂了,但实际上更加灵活,面向对象编程,拆分越细,拓展越灵活。

 

上一篇:Log4Net使用指南(转)


下一篇:Vue 实现div或者组件的「拖拽」功能,(PC和移动端都可以用)