zoukankan      html  css  js  c++  java
  • 拖拽-停止后仍是原来的位置

     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{100px;height:100px;background: red;position: absolute;left: 0;top:0;}
    3 </style>
    4 
    5 <body>
    6    <div class="box"></div>
    7 </body>
  • 相关阅读:
    利用数组创建的顺序表实现各种功能
    poj3181 Dollar Dayz
    【网络协议】TCP的流量控制机制
    6.6.1 F# 中函数调用的类型判断
    oracle ORA-06550
    为基于 x86 的 Android* 游戏选择合适的引擎
    linux下apache https 虚拟主机配置
    Hibernate学习笔记(六) — Hibernate的二级缓存
    08_Android中的SimpleAdapter的使用
    【从零学习openCV】IOS7人脸识别实战
  • 原文地址:https://www.cnblogs.com/sansancn/p/10884069.html
Copyright © 2011-2022 走看看