jQuery - mouseenterイベント、mouseoverイベント、mouseleaveイベント、mouseoutイベント

公開日:2018-12-28 更新日:2019-05-14
[jQuery]

1. 概要

マウスが要素の中に入った時に mouseenterイベント、mouseoverイベントが発生し、
要素の外に出た時に mouseleaveイベント、mouseoutイベントが発生します。
mouseenter と mouseover、mouseleave と mouseout の違いは、
親要素と子要素の間でマウスを行き来した時に、イベントが発生するかどうかです。

//マウスが要素の中に入った時
$(セレクタ).on("mouseenter", function(e) {
	処理;
});

//マウスが要素の外に出た時
$(セレクタ).on("mouseleave", function(e) {
	処理;
});

//マウスが要素の中に入った時(親子間の行き来でも発生する)
$(セレクタ).on("mouseover", function(e) {
	処理;
});

//マウスが要素の外に出た時(親子間の行き来でも発生する)
$(セレクタ).on("mouseout", function(e) {
	処理;
});

2.1 サンプル mouseenter, mouseleave

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>jQuery</title><style>body{color:#fff; background-color:#000;}</style></head>
<body style="padding:0px; margin:0px;">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <div style="padding:20px; padding-top:20px;">
    <div id="main" style="width:100px; height:90px; background-color:lightgray; color:black;">parent
      <div id="child" style="width:50px; height:50px; background-color:gray;">child</div>
    </div>
  </div>

  <div id="log" style="padding-left:20px;"></div>

  <script>

    $("#main").on("mouseenter", function(e) {
      log(e.target.id + ":mouseenter");
    });

    $("#main").on("mouseleave", function(e) {
      log(e.target.id + ":mouseleave");
    });

    //ログ出力
    var no = 1;
    function log(msg) {
      $("#log").append ('<div>' + no++ + ":" + msg + '</div>');
      if ($("#log div").length > 10) $("#log div:first").remove();
    }

  </script>
</body></html>

マウスをグレーの枠の中に入れると、ログが出力されます。
マウスを親要素と子要素の間で行き来しても、ログが出力されません。
実行結果:画面


2.2 サンプル mouseover, mouseout

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>jQuery</title><style>body{color:#fff; background-color:#000;}</style></head>
<body style="padding:0px; margin:0px;">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <div style="padding:20px; padding-top:20px;">
    <div id="main" style="width:100px; height:90px; background-color:lightgray; color:black;">parent
      <div id="child" style="width:50px; height:50px; background-color:gray;">child</div>
    </div>
  </div>

  <div id="log" style="padding-left:20px;"></div>

  <script>

    $("#main").on("mouseover", function(e) {
      log(e.target.id + ":mouseover");
    });

    $("#main").on("mouseout", function(e) {
      log(e.target.id + ":mouseout");
    });

    //ログ出力
    var no = 1;
    function log(msg) {
      $("#log").append ('<div>' + no++ + ":" + msg + '</div>');
      if ($("#log div").length > 10) $("#log div:first").remove();
    }

  </script>
</body></html>

マウスをグレーの枠の中に入れると、ログが出力されます。
マウスを親要素と子要素の間で行き来しても、ログが出力されます。
実行結果:画面