JS示例34-鼠标跟随事件

  • 2019 年 11 月 7 日
  • 筆記

一、知识要点

1、onmousemove 鼠标移动事件(要考虑页面滚动) 2、var X = ev.clientX; 3、var Y = ev.clientY + scrollTop; // 加上了滚动距离

二、源码参考

<!DOCTYPE HTML>  <html>    <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">      <title>鼠标跟随事件</title>      <style>          #div1 {              font-size: 10px;              width: 150px;              height: 150px;              background: red;              position: absolute;          }      </style>      <script>          window.onload = function () {                var oDiv = document.getElementById('div1');              document.onmousemove = function (ev) {                    var ev = ev || event; // 获取事件对象event                  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 滚动距离                    var X = ev.clientX;                  var Y = ev.clientY + scrollTop; // 加上了滚动距离                    oDiv.style.left = X + 'px';                  oDiv.style.top = Y + 'px';                    var show = "<div>(" + X + "," + Y + ")</div>";                  show += "<div>oDiv.style.left / X = " + X + "px</div>";                  show += "<div>oDiv.style.top / Y = " + Y + "px</div>";                  oDiv.innerHTML = show;              }            }      </script>  </head>    <body style="height: 2000px;">      <div id="div1"></div>  </body>    </html>

image

image.png