2010-08-29 39 views
1

我有一個CSS按鈕,具有正常,按下和懸停狀態。一切工作正常,除了當點擊發生時,我需要以某種方式知道風格是否應設置爲正常或懸停。也就是說,我需要知道鼠標光標是否仍然懸停在元素上的方法。如何用JavaScript實現這一點?在JavaScript中單擊自定義CSS按鈕後恢復懸停狀態?

回答

1

如果你關心用戶做一個mousedown,然後移動指針關閉(也許再次上)的按鈕,你可以做這樣的事情:

例:http://jsfiddle.net/7zUaj/1/

var mouseIsDown = false; // Track/remember mouse up/down state for the button 

    // Handle mouseenter and mouseleave 
$('div').hover(function() { 
    $(this).addClass('hover'); 
    if (mouseIsDown) 
     $(this).addClass('pressed'); // If mouse button was down, and user exited 
            // and reentered the button, add "pressed" 
}, function() { 
    $(this).removeClass('hover pressed'); // Remove both hover and pressed when 
              // the pointer leaves the button 
}) 
    // Handle the mousedown, track that it is down, and add "pressed" class 
.mousedown(function() { 
    mouseIsDown = true; 
    $(this).addClass('pressed'); 
}) 
// Handle the mouseup, track that it is now up, and remove the "pressed" class 
.mouseup(function() { 
    mouseIsDown = false; 
    $(this).removeClass('pressed'); 
}); 

// If user does mousedown, leaves the button, and does mouseup, 
//  track that it is now up 
$(document).mouseup(function() { 
    mouseIsDown = false; 
});​ 

在變量中跟蹤鼠標的狀態,並在按鈕的處理程序中設置mousedownmouseupmouseup也跟蹤在document級別。這將幫助.hover()mouseenter部分知道是否應設置pressed類。

(請注意,由於鼠標鬆開也被跟蹤在document,如果在頁面上的任何其他元素停止從冒泡的情況下,mouseup將不會被document檢測。)

編輯:做到這一點,因此document只跟蹤mouseup,和按鈕都跟蹤。

0

您的CSS中沒有:visited狀態?至於Javascript,OnMouseOver或JQuery mouseover,hovermouseenter(取決於你想做什麼)會告訴你什麼時候懸停發生。