事件绑定之鼠标悬停 -入门-进阶-精通-骨灰,来自锋利的jQuery

<!DOCTYPE html>
<html>
<head>
    <title>事件绑定之鼠标悬停</title>
    <script src="jquery-3.1.1.js"></script>
    <script>
                
    </script>
    <style type="text/css">
        .head{
            width: 200px;
            border: 1px solid #000;
            background-color: #ccc;
        }
        .content{
            display: none;
        }
    </style>
</head>
<body>
    <h2 class="head">事件绑定</h2>
    <div class="content">这是一段文字</div>
</body>
</html>        

HTML CSS代码如上下面开始jQuery代码

入门(click)

<script>
    $('.head').bind('click',function(){
       $(this).next().show();
    });    
</script>

增加效果 鼠标单击标题显示,在此单击隐藏

<script>
    $('.head').bind('click',function(){
        var $content = $(this).next();
        if($content.is(':visible')){
            $content.show();
        }else{
            $content.hide();
        }
    });
</script>

进阶--改变事件绑定类型

<script>
   $(function(){
$('.head').bind('mouseover',function(){
    $(this).next().show();
      }).bind('mouseout',function(){
        $('.content').hide();
      });
  }) 
</script>

精通--简写绑定事件

<script>
    $(function(){
        $('.head').mouseover(function(){
        $(this).next().show();
     }).mouseout(function(){
        $(this).next().hide();
        });
    })   
</script>

骨灰级本以为上面的简写很简单了,没想到jQuery还提供了更为简单的方法

$(function(){
    //hover()方法
    $('.head').hover(function(){
        $(this).next().show();
    },function(){
        $(this).next().hide();
    });
});

另外,hover()方法准确的来说是替代jQuery中的bind('mouseenter')和bind('mouseleave'),而不是替代bind('mouseover')和bind('mouseout')。因此当需要触发hover()方法的第2个函数时,需要用trigger('mouseleave')来触发,而不是trigger('mouseout')。