The box moves with the mouse (compatible with IE8)

demand

Make the box follow the mouse movement through JavaScript, and when the page appears scroll bar, the box will follow the mouse to move normally (compatible with IE8)

Insert picture description here

Code


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>div跟随鼠标移动</title>
  <style>
      div{
          width: 200px;
          height: 200px;
          background-color: skyblue;
          /*注意此处需要设置盒子的定位方式,否则后面设置盒子的偏移量无效*/
          position: absolute;
      }
      body{
          width: 2000px;
          height: 2000px;
      }
  </style>
  <script>
      window.onload = function () {
          let box = document.getElementById("box");
          let odj = document.documentElement;
          odj.onmousemove = function (event) {
              // 解决IE8对event的兼容性问题
              event = event || window.event;
              // 解决body和documentElement的兼容性问题(谷歌浏览器和其他浏览器的兼容性)
              var st = document.body.scrollTop || document.documentElement.scrollTop;
              var sl = document.body.scrollLeft || document.documentElement.scrollLeft;
              //设置盒子的水平偏移量	注意需要加上单位
              box.style.left = event.clientX + sl + "px";
              //设置盒子的垂直偏移量
              box.style.top = event.clientY + st + "px";
          };
      };
  </script>
</head>
<body>
<div id="box"></div>
</body>
</html>

Guess you like

Origin www.cnblogs.com/TomHe789/p/12687557.html