zoukankan      html  css  js  c++  java
  • 实现一个可以拖动的DIV。

    <div class= "xxx"></div>

    var
    dragging = false var position = null xxx.addEventListener('mousedown',function(e){ dragging = true position = [e.clientX, e.clientY] }) document.addEventListener('mousemove', function(e){ if(dragging === false) return null const x = e.clientX const y = e.clientY const deltaX = x - position[0] const deltaY = y - position[1] 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', function(e){ dragging = false })

        修改之后加上了注释。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
          .xxx{
             100px;
            height: 100px;
            background: red;
            left: 20px;
            top: 20px;
            position: relative;
          }
        </style>
    </head>
    <body>
       <div class="xxx"></div>
       <script>
        var dragging = false;  //拖拽的状态
        var position = null;  //当前的定位
         var xxx = document.querySelector(".xxx");
        //  console.log(xxx)
        xxx.addEventListener('mousedown',function(e){  //创建事件监听
          // console.log(1)
          dragging = true;  //拖拽状态
          position = [e.clientX,e.clientY];  //记录当前位置
        })
        //  移动的设置
        xxx.addEventListener('mousemove',function(e){
          // console.log(1)
          if(dragging === false) return  null;  //判断状态,如果为false返回空
          const x=e.clientX;   // 设置原位置坐标
          const y=e.clientY;
          const deltaX = x -position[0];   // 设置拖拽后位置的距离
          const deltaY = y - position[1];
          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];  //重新定位
        })
        xxx.addEventListener('mouseup',function(e){
          // console.log(1)
          dragging = false;   //鼠标抬起,改变状态
        })
       </script>
    </body>
    </html>
  • 相关阅读:
    [OpenGL]用OpenGL制作动画
    主管喜欢什么样的程序员
    windows下使用git管理代码,其中出现的问题的解决办法
    iOS7隐藏状态栏 status Bar
    [微信开发_02]环境搭建
    Matlab PCA 算法
    Git学习之msysGit环境支持
    Git学习之Git 暂存区
    Git学习之Git检出
    STL——(3)string容器
  • 原文地址:https://www.cnblogs.com/dy0302/p/13461889.html
Copyright © 2011-2022 走看看