鼠标事件

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

一、鼠标事件

事件名称描述
onclick当单击鼠标时运行脚本
ondblclick当双击鼠标时运行脚本
ondrag当拖动元素时运行脚本
ondragend当拖动操作结束时运行脚本
ondragenter当元素被拖动至有效的拖放目标时运行脚本
ondragleave当元素离开有效拖放目标时运行脚本
ondragover当元素被拖动至有效拖放目标上方时运行脚本
ondragstart当拖动操作开始时运行脚本
ondrop当被拖动元素正在被拖放时运行脚本
onmousedown当按下鼠标按钮时运行脚本
onmousemove当鼠标指针移动时运行脚本
onmouseout当鼠标指针移出元素时运行脚本
onmouseover当鼠标指针移至元素之上时运行脚本
onmouseup当松开鼠标按钮时运行脚本
onmousewheel当转动鼠标滚轮时运行脚本
onscroll当滚动元素滚动元素的滚动条时运行脚本

二、鼠标坐标

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        height: 3000px;
      }
    </style>
  </head>

  <body>
    <script>
      // 鼠标事件对象 MouseEvent
      document.addEventListener("click", function (e) {
        // 1. client 鼠标在 页面可视区域 的x和y坐标, 不会因为页面的滚动而改变
        console.log("x: ", e.clientX, "y: ", e.clientY);
        console.log("---------------------");

        // 2. page 鼠标在页面文档的x和y坐标 页面滚动值会变
        console.log("pageX: ", e.pageX, "pageY: ", e.pageY);
        console.log("---------------------");

        // 3. screen 鼠标在电脑屏幕的x和y坐标, 不受页面滚动影响
        console.log("screenX: ", e.screenX, "screenY: ", e.screenY);
      });
    </script>
  </body>
</html>

三、跟随鼠标的天使

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      img {
        position: absolute;
        top: 2px;
      }
    </style>
  </head>

  <body>
    <img src="images/angel.gif" alt="" />

    <script>
      var pic = document.querySelector("img");

      // 1. mousemove只要我们鼠标移动1px 就会触发这个事件
      document.addEventListener("mousemove", function (e) {
        // 2.核心原理: 每次鼠标移动, 我们都会获得最新的鼠标坐标, 
        // 把这个x和y坐标做为图片的top和left 值就可以移动图片
        var x = e.pageX;
        var y = e.pageY;
        console.log("x坐标是" + x, "y坐标是" + y);

        //3 . 千万不要忘记给left 和top 添加px 单位
        pic.style.left = x - 50 + "px";
        pic.style.top = y - 40 + "px";
      });
    </script>
  </body>
</html>