欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JavaScript实现跟随鼠标移动的盒子

时间:2021-06-22 09:37:21|栏目:JavaScript代码|点击:

本文实例为大家分享了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>
</head>
<style>
  div {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100px;
    height: 100px;
    background-color: red;
  }
</style>
 
<body>
  <div>111111111</div>
  <script>
    var div = document.getElementsByTagName('div')[0];
    div.onmousedown = function(e) {
      e = window.event || e;
      // 鼠标按下 获取鼠标距离页面左侧距离
      var x = e.clientX;
      // 获取鼠标距离页面上侧距离
      var y = e.clientY;
      // 元素距离页面左侧距离
      var elex = div.offsetLeft;
      // 元素距离页面上侧距离
      var eley = div.offsetTop;
      // 相减得到鼠标距离元素的距离
      var X = x - elex;
      var Y = y - eley;
      console.log(X, Y);
      document.onmousemove = function(e) {
          e = window.event || e;
          // 鼠标移动过程中 获取鼠标距离页面距离
          var movex = e.clientX;
          var movey = e.clientY;
          // 1.左侧边界值
          // 元素移动过程中距离页面左侧距离
          var leftx = movex - X;
          var lefty = movey - Y;
          // 1.左侧边界值
          if (leftx <= 0) {
            leftx = 0;
          }
          // 2.上侧边界值
          if (lefty <= 0) {
            lefty = 0
          }
          // 3.右侧边界值
          // 页面可视区宽 -元素宽
          var rightx = document.documentElement.clientWidth - div.offsetWidth;
          if (leftx >= rightx) {
            leftx = rightx
          }
          // 4.下侧边界值
          // 页面可视区高 -元素高
          var righty = document.documentElement.clientHeight - div.offsetHeight;
          if (lefty >= righty) {
            lefty = righty;
          }
          // 鼠标移动过程中 获取鼠标距离页面距离 - 鼠标距离元素的距离 =元素的left top值
          div.style.left = leftx + 'px';
          div.style.top = lefty + 'px';
 
 
 
        }
        // 抬起清除移动事件
      document.onmouseup = function() {
          document.onmousemove = null;
        }
        // 阻止默认事件
      return false;
 
    }
  </script>
</body>
 
</html>

上一篇:鼠标事件延时切换插件

栏    目:JavaScript代码

下一篇:javascript中的关于类型转换的性能优化

本文标题:JavaScript实现跟随鼠标移动的盒子

本文地址:http://www.codeinn.net/misctech/146356.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有