2010-02-17 77 views
4

所以我們可以說我有嵌套的div塊:問題與懸停事件和家長

<div class='nested'> 
<div class='nested'> 
    <div class='nested'></div> 
</div> 
</div> 

我想這種行爲:在一個div

  1. 徘徊。那個特殊的div改變了背景顏色,而它的孩子則沒有。
  2. 懸停在該div的孩子。再次,它改變了顏色,而它的孩子沒有,AND(重要)它的父母恢復到原來的顏色。
  3. 回到父div。孩子恢復到原來的顏色,父母再次改變顏色。

前兩個步驟很簡單:

$(function() { 
    $('.nested').bind('mouseenter',function() { 
    $(this).css('background-color','#EEE'); 
    $(this).parent().css('background-color','white'); 
    }).bind('mouseleave',function() { 
    $(this).css('background-color','white'); 
    }); 
}); 

但我碰釘子對最後一步,因爲當我進入一個孩子的div MouseEnter事件仍然在母體活性;我所做的只是讓它看起來不像。在父母上觸發mouseleave的唯一方法是完全退出嵌套塊並再次輸入。有沒有解決的辦法?

回答

4

向父級添加一個mouseleave事件,並刪除父級的顏色。

$(function() { 
    $('.nested').bind('mouseenter',function() { 
    $(this).css('background-color','#EEE'); 
    $(this).parent().css('background-color','white'); 
    }).bind('mouseleave',function() { 
    $(this).css('background-color','white'); 
    // put the color back on the parent 
    $(this).parent().css('background-color', '#EEE'); 
    }); 

    // remove the color from the parent 
    $(".parent").bind("mouseleave", function() { 
    $(this).css('background-color','white'); 
    }); 
});