<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
100px;
height: 100px;
background: blue;
position: absolute;
left: 0;top: 0;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
class Grat{
constructor(){
this.box =document.querySelector(".box");
this.m = this.move.bind(this);
this.u = this.up.bind(this);
this.addEvent();
console.log(this.box)
this.getData();
}
addEvent(){
this.box.addEventListener("mousedown",this.down.bind(this));
}
down(eve){
console.log(1);
this.downE = eve || window.event;
document.addEventListener("mousemove",this.m);
document.addEventListener("mouseup",this.u);
}
move(eve){
var e = eve ||window.event;
this.box.style.left = e.clientX - this.downE.offsetX +"px";
this.box.style.top = e.clientY - this.downE.offsetY +"px";
}
up(){
document.removeEventListener("mousemove",this.m);
document.removeEventListener("mouseup",this.u);
this.setDate();
}
//抬起记住位置
setDate(){
let obj ={
left:this.box.offsetLeft,
top:this.box.offsetTop,
}
localStorage.setItem("obj",JSON.stringify(obj));
}
//获取位置
getData(){
var obj = localStorage.getItem("obj") ? JSON.parse(localStorage.getItem("obj")) :{left:0,top:0};
this.box.style.left = obj.left+"px";
this.box.style.top = obj.top+"px";
}
}
new Grat;
</script>
</html>