实现效果叙述
页面中实现拖拽效果,为了要使两个元素实现不同的效果,一个有边界限定,一个没有边界限定。所以要在继承父元素的基础上添加自己的方法。
HTML代码如下:
<div id="box1"></div>
<div id="box2"></div>
CSS代码如下:
div{width: 100px;height: 100px;position: absolute;left:0;}
#box1{background:red;top:0;}
#box2{background:blue;top:130px;}
用混合继承方式实现
JS代码如下:
class Drag{
constructor(ele){
this.ele = ele;
this.addEvent();
}
addEvent(){
var that = this;
this.ele.onmousedown = function(eve){
that.downE = eve || window.event;
document.onmousemove = function(eve){
that.moveE = eve || window.event;
that.move();
}
document.onmouseup = function(){
that.up();
}
}
}
move(){
this.ele.style.left = this.moveE.clientX - this.downE.offsetX + "px";
this.ele.style.top = this.moveE.clientY - this.downE.offsetY + "px";
}
up(){
document.onmousemove = null;
}
}
class SmallDrag extends Drag{
constructor(ele){
super(ele);
}
move(){
let l = this.moveE.clientX - this.downE.offsetX;
let t = this.moveE.clientY - this.downE.offsetY;
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);
用ES6的class继承方式实现
JS代码如下:
class Drag{
constructor(ele){
this.ele = ele;
this.addEvent();
}
addEvent(){
var that = this;
this.ele.onmousedown = function(eve){
that.downE = eve || window.event;
document.onmousemove = function(eve){
that.moveE = eve || window.event;
that.move();
}
document.onmouseup = function(){
that.up();
}
}
}
move(){
this.ele.style.left = this.moveE.clientX - this.downE.offsetX + "px";
this.ele.style.top = this.moveE.clientY - this.downE.offsetY + "px";
}
up(){
document.onmousemove = null;
}
}
class SmallDrag extends Drag{
constructor(ele){
super(ele);
}
move(){
let l = this.moveE.clientX - this.downE.offsetX;
let t = this.moveE.clientY - this.downE.offsetY;
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);