拖拽一个小方块,代码如下:
class Drag{
constructor(){
this.box = document.getElementById("box");
this.getPos();
this.addEvent();
}
getPos(){
this.box.style.left = (localStorage.getItem("left") || 0) + "px";
this.box.style.top = (localStorage.getItem("top") || 0) + "px";
}
addEvent(){
var that = this;
this.box.onmousedown = function(eve){
var e = eve || window.event;
that.down(e);
}
}
down(downE){
var that = this;
document.onmousemove = function(eve){
var e = eve || window.event;
that.move(downE, e);
}
document.onmouseup = function(){
that.up()
}
}
move(downE, moveE){
this.box.style.left = moveE.clientX - downE.offsetX + "px";
this.box.style.top = moveE.clientY - downE.offsetY + "px";
}
up(){
document.onmousemove = document.onmouseup = null;
localStorage.setItem("left",this.box.offsetLeft);
localStorage.setItem("top",this.box.offsetTop);
}
}
new Drag();