首页 > 其他 > 详细

拖拽-停止后仍是原来的位置

时间:2019-05-17 23:31:22      阅读:189      评论:0      收藏:0      [点我收藏+]
 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>

 

拖拽-停止后仍是原来的位置

原文:https://www.cnblogs.com/sansancn/p/10884069.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!