实现页面上两个DOM元素的操作,通过继承的方式
class Drag{
constructor(ele){
this.ele = ele;
this.m = this.move.bind(this);
this.u = this.up.bind(this);
this.addEvent();
}
addEvent(){
this.ele.addEventListener("mousedown",this.down.bind(this))
}
down(eve){
var e = eve || window.event;
this.x = e.offsetX;
this.y = e.offsetY;
document.addEventListener("mousemove",this.m);
document.addEventListener("mouseup",this.u);
}
move(eve){
var e = eve || window.event;
this.ele.style.left = e.clientX - this.x + "px";
this.ele.style.top = e.clientY - this.y + "px";
}
up(){
document.removeEventListener("mousemove",this.m);
document.removeEventListener("mouseup",this.u);
}
}
class SmallDrag extends Drag{
constructor(ele){
super(ele)
}
move(eve){
var e = eve || window.event;
var l = e.clientX - this.x;
var t = e.clientY - this.y;
if(l < 0){
l = 0;
}
if(t < 0){
t = 0;
}
this.ele.style.left = l + "px";
this.ele.style.top = t + "px";
}
}
var obox1 = document.getElementById("box1")
var obox2 = document.getElementById("box2")
new Drag(obox1);
new SmallDrag(obox2);
原文地址:https://www.cnblogs.com/1179929172-zh/p/11444559.html