jQuery經常使用事件方法——mouseenter、mouseleave、hover方法

jQuery經常使用事件方法
  • jQuery事件方法與原生Js事件方法名稱相似,不須要寫on,經過jQuery對象打點調用,括號內參數是事件函數javascript

  • mouseenter()方法:鼠標進入一個元素觸發的事件java

  • mouseleave()方法:鼠標離開一個元素觸發的事件jquery

  • 注意:mouseenter和mouseleave沒有事件冒泡,在使用時替換mouseover和mouseout更加合適函數

下面是代碼對比:code

<div class="parent">
   <div class="box"></div>
</div>
 <script src="../jq/jquery-1.12.4.min.js"></script>
   <script>
     var $box = $(".box");
     var $parent = $(".parent");
     //對比mouseenter、mouseleave 和 mouseover、mouseout
     // 對比mouseenter、mouseleave 不冒泡
     $box.mouseenter(function(){
        console.log("box mouse in")
      })
     $box.mouseleave(function(){
        console.log("box mouse out")
     })
     $parent.mouseenter(function(){
        console.log("parent mouse in")
     })
     $parent.mouseleave(function(){
        console.log("parent mouse out")
     })

//mouseover、mouseout  冒泡
$box.mouseover(function(){
    console.log("box mouse in")
})
$box.mouseout(function(){
    console.log("box mouse out")
})
$parent.mouseover(function(){
    console.log("parent mouse in")
})
$parent.mouseout(function(){
    console.log("parent mouse out")
})

  • hover()方法:至關於將mouseenter和mouseleave事件進行了合寫對象

    hover(鼠標移上執行的事件函數,鼠標離開執行的事件函數)blog

//hover() 對mouseenter和mouseleave合併書寫
//$box.hover(function () { }, function () { })
$box.hover(function(){
    $box.addClass("big");
},function(){
   $box.removeClass("big")
})
相關文章
相關標籤/搜索