码迷,mamicode.com
首页 > Web开发 > 详细

js简单实现拖拽功能

时间:2021-06-02 15:25:39      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:prot   style   ack   html   sel   new   height   拓展   absolute   

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);

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

 

js简单实现拖拽功能

标签:prot   style   ack   html   sel   new   height   拓展   absolute   

原文地址:https://www.cnblogs.com/chao202426/p/14824808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!