之前写过鼠标拖动视觉效果。但并未使用面向对象来书写。页面刷新后,无法保存在上次鼠标抬起的位置。这次补充这一效果。
依然使用DIV加入样式来模拟。
<style>
#box{width: 100px;height: 100px;background: red;position: absolute;left: 0;top:0;}
</style>
<body>
<div id="box"></div>
</body>
<script>
class Drag{
constructor(){
// 引入元素。
this.box = document.getElementById("box");
}
addEvent(){
// 事件绑定。
var that = this;
// 鼠标按下。
this.box.onmousedown = function(eve){
var downE = eve || window.event;
// 鼠标移动。
document.onmousemove = function(eve){
var moveE = eve || window.event;
that.move(downE, moveE);
}
// 鼠标抬起。
document.onmouseup = function(){
that.up();
}
}
}
// 按下鼠标移动时获取坐标值。
move(d,m){
this.box.style.left = m.pageX - d.offsetX + "px";
this.box.style.top = m.pageY - d.offsetY + "px";
}
// 鼠标抬起时,Gong元素。瞬间获得。抬起时的鼠标坐标。并保持在抬起位置。
up(){
document.onmousemove = null;
var pos = {
x:this.box.offsetLeft,
y:this.box.offsetTop
}
// 将抬起时的位置。储存在本地存储中。下次打开页面还在上次抬起的位置。
localStorage.setItem("weiZhi",JSON.stringify(pos));
}
// 本地存储坐标。
getPos(){
var p = localStorage.getItem("weiZhi")
if(p){
p = JSON.parse(p);
}else{
p = {x:0,y:0}
}
this.box.style.left = p.x + "px";
this.box.style.top = p.y + "px";
}
}
var d = new Drag();
d.getPos()
d.addEvent();
</script>