Skip to content

mouseover/mouseout

鼠标移入: mouseover 鼠标移出: mouseout

html
<!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>js</title>
    <style>
      body {
        padding: 50px;
      }
      #wrapper {
        width: 200px;
        height: 200px;
        background-color: red;
      }
      #inner {
        width: 100px;
        height: 100px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <div id="inner"></div>
    </div>
    <script>
      var wrapper = document.getElementById("wrapper"),
        overCount = 0,
        outCount = 0;

      // 鼠标移入
      wrapper.addEventListener("mouseover", function (e) {
        overCount += 1;
        console.group("mouseover");
        console.log("overCount: ", overCount);
        console.log("target: ", e.target);
        console.groupEnd();
      });

      // 鼠标移出
      wrapper.addEventListener("mouseout", function (e) {
        outCount += 1;
        console.group("mouseout");
        console.log("outCount: ", outCount);
        console.log("target: ", e.target);
        console.groupEnd();
      });
    </script>
  </body>
</html>

mouseover_out.gif

mouseenter/mouseleave

鼠标移入: mouseenter 鼠标移出: mouseleave

html
<!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>js</title>
    <style>
      body {
        padding: 50px;
      }
      #wrapper {
        width: 200px;
        height: 200px;
        background-color: red;
      }
      #inner {
        width: 100px;
        height: 100px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <div id="inner"></div>
    </div>
    <script>
      var wrapper = document.getElementById("wrapper"),
        overCount = 0,
        outCount = 0;

      // 鼠标移入
      wrapper.addEventListener("mouseenter", function (e) {
        overCount += 1;
        console.group("mouseenter");
        console.log("overCount: ", overCount);
        console.log("target: ", e.target);
        console.groupEnd();
      });

      // 鼠标移出
      wrapper.addEventListener("mouseleave", function (e) {
        outCount += 1;
        console.group("mouseleave");
        console.log("outCount: ", outCount);
        console.log("target: ", e.target);
        console.groupEnd();
      });
    </script>
  </body>
</html>

mouseenter_leave.gif

两种事件触发条件的区别:

以上代码及其测试效果(gif 图)可以看出: mouseover/mouseout: 事件源及其所有子元素节点都可以触发 mouseenter/mouseleave: 只有事件源可以触发

Released under the MIT License.