• 实现一个div的拖拽效果


    实现思路:

    1. 鼠标按下开始拖拽
    2. 记录摁下鼠标时的鼠标位置以及元素位置
    3. 拖动鼠标记下当前鼠标的位置
    4. 鼠标当前位置-摁下时鼠标位置= 鼠标移动距离
    5. 元素位置= 鼠标移动距离+鼠标摁下时元素的位置
              class Drag {
                  //构造函数
                  constructor(el) {
                      this.el = el;
                      //鼠标摁下时的元素位置
                      this.startOffset = {};
                      //鼠标摁下时的鼠标位置
                      this.startPoint = {};
                      let move = (e) => {
                          this.move(e);
                      };
                      let end = (e) => {
                          document.removeEventListener("mousemove", move);
                          document.removeEventListener("mouseup", end);
                      };
                      el.addEventListener("mousedown", (e) => {
                          this.start(e);
                          document.addEventListener("mousemove", move);
                          document.addEventListener("mouseup", end);
                      })
                  }
                  //摁下时的处理函数
                  start(e) {
                      let { el } = this;
                      this.startOffset = {
                          x: el.offsetLeft,
                          y: el.offsetTop
                      }
                      this.startPoint = {
                          x: e.clientX,
                          y: e.clientY
                      }
                  }
                  //鼠标移动时的处理函数
                  move(e) {
                      let { el, startOffset, startPoint } = this;
                      let newPoint = {
                          x: e.clientX,
                          y: e.clientY
                      }
                      let dis = {
                          x: newPoint.x - startPoint.x,
                          y: newPoint.y - startPoint.y,
                      }
                      el.style.left = dis.x + startOffset.x + "px";
                      el.style.top = dis.y + startOffset.y + "px";
                  }
              }
      
              (function () {
                  let box = document.querySelector("#box");
                  let dragbox = new Drag(box);
              })()
     
  • 相关阅读:
    poj 3669 Meteor Shower
    poj 3009 Curling 2.0
    poj 1979 Red and Black
    区间内素数的筛选
    九度oj 题目1347:孤岛连通工程
    poj 3723 Conscription
    poj 3255 Roadblocks
    Luogu P3975 [TJOI2015]弦论
    AT2165 Median Pyramid Hard 二分答案 脑洞题
    后缀自动机多图详解(代码实现)
  • 原文地址:https://www.cnblogs.com/yinping/p/10697083.html
Copyright © 2020-2023  润新知