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

概述

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

最后

以上就是苗条烧鹅为你收集整理的鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动的全部内容,希望文章能够帮你解决鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部