2010-12-03 262 views
0

當我嘗試這個。jQuery懸停不起作用

<ul id="sub_navigation"><li>A</li><li>B</li></ul> 

與jQuery懸停這樣

$(function() { 
    $('#sub_navigation').hover(function() { 
     $(this).addClass('hovered'); 
    }, 
    function() { 
    $(this).removeClass('hovered'); 
    }); 

    alert($('#sub_navigation').is('.hovered')); 

}); 

總是返回false當我徘徊在sub_navigation。

有什麼問題嗎?

感謝

+0

在您將鼠標移動到元素之前,您正在執行`alert'。 – 2010-12-03 19:06:09

回答

3

返回錯誤是正常的在這裏,因爲你提醒在頁面加載時,而不是當您懸停。例如,這將返回true

$(function() { 
    $('#sub_navigation').hover(function() { 
     $(this).addClass('hovered'); 
     alert($('#sub_navigation').is('.hovered')); 
    }, function() { 
     $(this).removeClass('hovered'); 
    }); 
}); 

You can test it here


但請記住,如果你這樣做只是爲了造型,使用:hover CSS僞類會在所有的瀏覽器IE6,除了這裏(沒有的JavaScript):

#sub_navigation:hover { color: red; } 

Test it out here