jQuery里的mouseover与mouseenter事件类型区别

JQ里面有mouseover和mouseenter  2个事件类型干着差不多的活,用不好经常出现些小问题。

今天我解释一下原理:

事件类型翻译:

mouseover     鼠标移上

mouseenter    鼠标移进 


jQuery的 mouseover 绝对等于原生js的 onmouseover,但使用起来是往往会有些问题。

原生js没有 onmouseenter 的事件类型,jQuery内部给它封装了新的事件类型也就是 mouseenter 来解决这个问题。

 ( 对应还有鼠标离开 onmouseout和mouseleave同理 )

线上demo:  http://jsbin.com/gihaya/1/

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>mouseover和mouseenter区别</title>
  <style>
  .over-and-enter div{background:#ccc;padding:20px;width:30%;float:left;margin: 0 10px;}
  .over-and-enter h2{background: #fff;}
  </style>
  <script type="text/javascript">
  var x=0;
  var y=0;
  $(function(){
      $('.over').mouseover(function(){
          $('.over span').html( x+=1 );
      });
      $('.enter').mouseenter(function(){
          $('.enter span').html( y+=1 );
      });
  });
  </script>
</head>
<body>
<div class="over-and-enter">
    <p>不论鼠标<b>移上被选元素或其子元素</b>,都会触发 mouseover 事件。</p>
    <p>鼠标移进被选元素,不管在其内部如何移动,<b>只触发一次</b> mouseenter 事件。</p>
    <div class="over">
    <h2>被触发的 mouseover 事件:<span></span></h2>
    </div>
    <div class="enter">
    <h2>被触发的 mouseenter 事件:<span></span></h2>
    </div>
</div>
</body>
</html>

工作中可能遇到的bug。

线上demo: http://jsbin.com/lacepe/1/

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>mouseenter和mouseleave</title>
    <style>
    .father{width:100%;height:200px;background: #ccc;border: 1px solid #000;display: none;cursor: pointer;}
    .children{width: 95%;height:150px;background: #eee;margin: 10px auto;cursor: pointer;}
    </style>
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script>
    $(function(){
        // js原生事件有onmouseover和onmouseout,功能是绝对等于jQ的mouseover和mouseout
        $('button').mouseover(function(){
            $('.father').show();
        });
        // jQuery封装了2个新的事件,mouseenter和mouseleave来检测移进/出被选元素的次数
        $('.father').mouseout(function(){
            $('.father').hide();
        });
        // demo的bug把mouseout事件类型换成mouseleave即可。

        // 总结:
        // 我们jquery 里面 不太用  mouseover      mouseout 
        // 而我们喜欢用            mouseenter     mouseleave
    })
    </script>
</head>
<body>
    <button>鼠标过来</button>
    <div class="father">
        我是下拉菜单,<b>离开我的范围我才隐藏起来</b><div class="children">我可能是下拉菜单的内容,<b>移到我这里看看。</b></div>
    </div>
</body>
</html>

解决办法:demo的bug把mouseout事件类型换成mouseleave即可。

总结:

我们jquery 里面 不太用   mouseover             mouseout

而我们喜欢用                    mouseenter            mouseleave

原文地址:https://www.cnblogs.com/Megasu/p/4543688.html