我是靠谱客的博主 苗条烧鹅,这篇文章主要介绍鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动,现在分享给大家,希望可以做个参考。

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

<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>
</head>

<body>
  <div class="box">

  </div>
</body>

</html>
<style>
  .box {
    width: 200px;
    height: 200px;
    background-color: red;
    position: absolute;
    top: 0;
    left: 0;
  }
</style>
<script>
  var box = document.querySelector(".box")
  box.addEventListener('mousedown', function (e) {
    var x = e.pageX - box.offsetLeft   //    鼠标距离页面位置 - 盒子距离左边的位置 =   鼠标点击位置到盒子边缘的距离
    var y = e.pageY - box.offsetTop
    document.addEventListener('mousemove',moveS)
      function moveS(e) {
      box.style.left = e.pageX - x + 'px'   //鼠标所在位置  -   鼠标到盒子边缘的距离 =  盒子距离左边的距离
      box.style.top = e.pageY - y + 'px'
      }
      document.addEventListener('mouseup',function (e) {
    document.removeEventListener('mousemove',moveS)
        
      })
    })
</script>

最后

以上就是苗条烧鹅最近收集整理的关于鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动的全部内容,更多相关鼠标按下盒子跟随鼠标移动内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部