温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用JavaScript实现一个拉拽效果

发布时间:2020-11-21 14:59:12 来源:亿速云 阅读:120 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关使用JavaScript实现一个拉拽效果,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

代码如下

<!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>

   #drag {

    background: aqua;
    width: 200px;
    height: 200px;
    position: absolute;
    -moz-user-select: none;
    -khtml-user-select: none;
    user-select: none;

   }

   #parent {
    position: relative;
    background: #cde4dc;
    height: 80vh;
    overflow: hidden;

   }

  </style>
 </head>

<body>
  <section id="parent">
   <div id="drag"><div>这是一个测试</div></div>
  </section>
  <script type="text/javascript">

   //自执行函数,需要拖拽的元素需要设置position:absolute,父元素position:relative
   //有传父亲节点、若无则默认body为父节点

   ((parent, children, mouseType) => {

    if (!children) return;
    let childrenDiv = document.querySelector(children);
    childrenDiv.style.position = 'absolute';
    let parentDiv = parent

     &#63; document.querySelector(parent)
     : document.querySelector('body');

    let isDown = false;

    let x,
     y,
     l,
     t = 0;

    childrenDiv.onmousedown = function (e) {

     x = e.clientX;
     y = e.clientY;

     // 获取左部和底部的偏移量

     l = childrenDiv.offsetLeft;
     t = childrenDiv.offsetTop;
     isDown = true;
     childrenDiv.style.cursor = mouseType || 'move';

    };

    // 鼠标移动

    window.onmousemove = function (e) {

     if (!isDown) {

      return;

     }

     //获取移动后的x和y坐标

     let nx = e.clientX;
     let ny = e.clientY;

     //获取父元素的宽高

     let parentWidth = parentDiv.clientWidth;
     let parentHeight = parentDiv.clientHeight;

     //获取子元素的宽高

     let childrenWidth = childrenDiv.clientWidth;
     let childrenHight = childrenDiv.clientHeight;

     // 计算移动后的左偏移量和顶部偏移量

     let nLeft = nx - (x - l);
     let nTop = ny - (y - t);
     let nRight = nLeft + childrenWidth;
     let nBottom = nTop + childrenHight;
     nLeft = nLeft <= 0 &#63; 0 : nLeft; //判断左边距离是否越界
     nTop = nTop <= 0 &#63; 0 : nTop; //判断上边距离是否越界
     //判断右边距离大于父元素宽度

     if (nRight >= parentWidth) {

      nLeft = parentWidth - childrenHight;

     }

     // 判断下边界是否越界

     if (nBottom >= parentHeight) nTop = parentHeight - childrenHight;
     childrenDiv.style.left = nLeft + 'px';
     childrenDiv.style.top = nTop + 'px';

    };

    // 鼠标抬起事件
    document.onmouseup = function (e) {
     //鼠标抬起
     isDown = false;

     childrenDiv.style.cursor = 'default';

    };

   })('#parent', '#drag', 'move');

  </script>
 </body>
</html>

使用JavaScript实现一个拉拽效果

关于使用JavaScript实现一个拉拽效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI