likes
comments
collection
share

前端三大家族之offset,然后做出鼠标的拖拽效果

作者站长头像
站长
· 阅读数 32

offset 用于获取元素的偏移量:

可以获取元素距离带有定位的父元素的位置【注意条件,需要有定位】,如果父元素没有定位,则会向上寻找直到找到带有定位的那个父级元素offsetTop:获取到元素距离带有定位的父元素的顶部的距离offsetLeft:获取到元素距离带有定位的父元素的左边的距离

可以获取元素本身的大小(获取到的值不带单位), padding + width + borderoffsetWidth:获取到元素的宽度offsetHeight:获取到元素的高度

了解了 offsetTop 和 offsetLeft 之后我们就可以做一个拖拽元素的小练习了,实现思路如下图:前端三大家族之offset,然后做出鼠标的拖拽效果

代码如下:

<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      padding: 0;
      margin: 0;
    }
    body{
      position: relative;
    }
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
    }
  </style>
</head>
<body>

  <div class="box"></div>

  <script>
    let box = document.querySelector('.box')
    /**
     * 应该先获取到鼠标在盒子里面的位置
     * 鼠标在盒子内的位置 = 鼠标在页面的位置 - 盒子距离屏幕边的距离
     * 盒子距离屏幕边的距离 = 鼠标在页面的位置 - 鼠标在元素内的位置
    */

    //鼠标按下
    box.addEventListener('mousedown',function(e){
      let mouseX = e.pageX - box.offsetLeft
      let mouseY = e.pageY - box.offsetTop

      //鼠标移动时间方法,这个方法一定要抽离出来,这样才能通过 removeEventListener 将监听事件移除
      var move = function(e){
        let left = e.pageX - mouseX
        let top = e.pageY - mouseY
        //实现拖拽
        box.style.left = left + 'px'
        box.style.top = top + 'px'

        //鼠标抬起
        box.addEventListener('mouseup',function(e){
          //移除鼠标移动监听,结束跟随2
          box.removeEventListener('mousemove', move)
        })

      }

      box.addEventListener('mousemove', move)

    })

  </script>
  
</body>
</html>
转载自:https://segmentfault.com/a/1190000041853858
评论
请登录