1 <script src="../cookie.js"></script> 2 <script> 3 4 class Drag{ 5 constructor(){ 6 this.box = document.querySelector(".box"); 7 8 this.init() 9 this.getPos() 10 } 11 init(){ 12 var that = this; 13 14 // 因为使用事件监听绑定事件,删除事件时要找原函数,所以提前使用bind计算出改变this之后的新函数 15 this.m = that.move.bind(that); 16 this.u = that.up.bind(that); 17 18 this.box.addEventListener("mousedown",function(eve){ 19 var e = eve || window.event; 20 that.x = e.offsetX; 21 that.y = e.offsetY; 22 // console.log(this) //指向box 23 // 使用bind改变this指向之后的新函数,作为事件处理函数 24 document.addEventListener("mousemove",that.m) 25 document.addEventListener("mouseup",that.u) 26 // console.log(this) 27 // 可以看到位置坐标 28 }) 29 } 30 move(eve){ 31 var e = eve || window.event; 32 // console.log(this) 33 this.box.style.left = e.pageX - this.x + "px"; 34 this.box.style.top = e.pageY - this.y + "px"; 35 } 36 up(){ 37 // 因为bind生成的函数被提前保存了,所以删除的时候找到的还是同一个函数 38 document.removeEventListener("mousemove",this.m) 39 document.removeEventListener("mouseup",this.u) 40 this.setCookie(); 41 } 42 setCookie(){ 43 var pos = { 44 x:this.box.offsetLeft, 45 y:this.box.offsetTop 46 } 47 setCookie("pos",JSON.stringify(pos),{ 48 expires:3 49 }) 50 } 51 getPos(){ 52 this.pos = JSON.parse(getCookie("pos")) 53 // console.log(this.pos) 54 this.box.style.left = this.pos.x + "px"; 55 this.box.style.top = this.pos.y + "px"; 56 } 57 } 58 59 60 new Drag() 61 </script>
1 <style> 2 .box{width:100px;height:100px;background: red;position: absolute;left: 0;top:0;} 3 </style> 4 5 <body> 6 <div class="box"></div> 7 </body>