JS实现拖拽(原生)

本文详细介绍了一个简单的拖拽功能实现过程,包括使用onmousedown、onmousemove和onmouseup事件来控制元素的位置,使元素能够跟随鼠标在页面中移动。代码示例展示了如何通过JavaScript获取鼠标和元素的坐标,并实时更新元素的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拖拽的原理:三个事件 onmousedown、onmousemove、onmousemove

1、鼠标按下,触发onmousedown,获取鼠标坐标x,y,获取元素坐标x,y

   通过event.clientX、event.clientY获取鼠标位置的坐标

 let x = e.clientX - box.offsetLeft;     //鼠标点击坐标距离盒子左边缘的距离
 let y = e.clientY - box.offsetTop;     //鼠标点击坐标距离盒子上边缘的距离

2、设置元素left、top值,(元素要设置position:absolute)

 box.style.left = ev.clientX - x + 'px';
 box.style.top = ev.clientY - y + 'px';

3、放开鼠标取消dom事件

下面是详细代码:我只开了横向移动

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background: red;
      position: absolute
    }

  </style>
</head>

<body style="position: relative;overflow: hidden;">
  <div id="box">

  </div>

  <script>
    window.onload = function () {
      let box = document.getElementById('box')
      box.onmousedown = function (ev) {
        let e = ev || event;
        let x = e.clientX - box.offsetLeft;     //鼠标点击坐标距离盒子左边缘的距离
        let y = e.clientY - box.offsetTop;     //鼠标点击坐标距离盒子上边缘的距离
        document.onmousemove = function (ev) {
          let e = ev || event;
          box.style.left = ev.clientX - x + 'px';
          box.style.top = ev.clientY - y + 'px';
          
          let bodyScreenX = ev.screenX
          let bodyClientWidth = document.body.clientWidth
          
          document.onmouseup = function (ev) {
            if (ev.clientX - x < 0) {
              box.style.left = 0
            } else if (bodyScreenX > bodyClientWidth) {
              box.style.right = 0
              box.style.left = bodyClientWidth - 100 + 'px'
            }
            document.onmousemove = null;
            document.onmouseup = null;
          }
        }
      }
    }

  </script>
</body>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值