码迷,mamicode.com
首页 > 其他好文 > 详细

鼠标拖拽元素以及继承原生代码

时间:2019-09-02 09:32:21      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:页面   top   div   bin   sem   继承   lis   lld   tor   

实现页面上两个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);

鼠标拖拽元素以及继承原生代码

标签:页面   top   div   bin   sem   继承   lis   lld   tor   

原文地址:https://www.cnblogs.com/1179929172-zh/p/11444559.html

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