在JavaScript中单击自定义CSS按钮后恢复悬停状态?

时间:2010-08-29 15:13:50

标签: javascript html css

我有一个CSS按钮,具有正常,按下和悬停状态。一切正常,但是当点击发生时,我需要以某种方式知道样式是应该设置为正常还是悬停。也就是说,我需要一种方法来了解鼠标光标是否仍然悬停在元素上。如何通过JavaScript实现这一目标?

2 个答案:

答案 0 :(得分: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级别进行跟踪。这有助于mouseenter .hover()部分知道是否应该设置pressed课程。

(请注意,因为鼠标在document上也会被跟踪,如果页面上有任何其他元素阻止事件冒泡,则mouseup将不会被检测到document。)

编辑:这样,document仅跟踪mouseup,按钮跟踪两者。

答案 1 :(得分:0)

您的CSS中没有:visited状态?至于Javascript,OnMouseOver或JQuery mouseoverhovermouseenter(取决于您想要做什么)会告诉您何时发生悬停。