【发布时间】:2010-08-29 23:49:03
【问题描述】:
我有一个具有正常、按下和悬停状态的 CSS 按钮。一切正常,除了当点击发生时,我需要以某种方式知道样式应该设置为正常还是悬停。也就是说,我需要一种知道鼠标光标是否仍然悬停在元素上的方法。如何使用 JavaScript 实现这一目标?
【问题讨论】:
标签: javascript html css
我有一个具有正常、按下和悬停状态的 CSS 按钮。一切正常,除了当点击发生时,我需要以某种方式知道样式应该设置为正常还是悬停。也就是说,我需要一种知道鼠标光标是否仍然悬停在元素上的方法。如何使用 JavaScript 实现这一目标?
【问题讨论】:
标签: javascript html css
如果您担心用户执行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;
});
鼠标的状态在一个变量中进行跟踪,并在mousedown 和mouseup 的按钮处理程序中设置。 mouseup 也在document 级别进行跟踪。这将帮助.hover() 的mouseenter 部分知道它是否应该设置pressed 类。
(请注意,因为 mouseup 也会在 document 上进行跟踪,如果页面上有任何其他元素阻止事件冒泡,document 将不会检测到 mouseup .)
编辑:这样document 只跟踪mouseup,而按钮同时跟踪两者。
【讨论】:
您的 CSS 中没有:visited 状态?至于 Javascript,OnMouseOver 或 JQuery mouseover、hover 或 mouseenter(取决于您想要做什么)会告诉您何时发生悬停。
【讨论】: