zoukankan      html  css  js  c++  java
  • mouse事件实现可拖拽的div

    写在前面

    这个需求的实现重点就是鼠标 mouse 的三个事件的监听处理。即 mousedownmousemovemouseup

    并且,可以被拖拽随意移动的元素一般是绝对定位的元素。

    实现方法

    <body>
      <div id="xxx"></div>
    </body>
    
    #xxx{
      position: absolute;
       100px;
      height: 100px;
      border: 1px solid red;
    }
    
    let dragging = false;
    let position = [];
    xxx.addEventListener('mousedown',(e)=>{
      dragging = true;
      position = [e.clientX, e.clientY];
    })
    
    document.addEventListener('mousemove',(e)=>{
      if(!dragging) return;
      const x = e.clientX;
      const y = e.clientY;
      const deltaX = x - position[0];
      const deltaY = y - position[1];
      console.log(deltaX,deltaY);
      const left = parseInt(xxx.style.left || 0);
      const top = parseInt(xxx.style.top || 0);
      xxx.style.left = left + deltaX + 'px';
      xxx.style.top = top + deltaY + 'px';
      position = [x,y];
    })
    
    document.addEventListener('mouseup',(e)=>{
      dragging = false;
    })
    

    注意事项:

    1. style.left 得到的是带有 px 单位的值,需要进行数值转化。
    2. style.left 的值可能为 undefined,parseInt(undefined) = NaN,因此记得保留值 || 0。
    3. mousedown 必须是绑定在 xxx 元素上,为了使得移动流畅,mousemove 一般绑定在 document 上,mouseup也是。
  • 相关阅读:
    全站301跳转 PHP
    linux flush memcache缓存
    php Memcache
    PHP MemCached win安装
    windows下安装memcache
    2013 年最好的 20 款免费 jQuery 插件
    License Manager 10.3启动失败解决方法
    .ecp认证文件(10.3版本)
    ArcGIS 10.3 安装及破解
    win7下安装MYSQL报错:"MYSQL 服务无法启动"的3534问题
  • 原文地址:https://www.cnblogs.com/lovevin/p/13412755.html
Copyright © 2011-2022 走看看