这似乎是一个非常普遍的问题,虽然我已经尝试过使用 addClass/removeClass 而不是直接 CSS 操作的建议,并且我已经尝试过 mouseleave/mouseout 但两者都会导致问题。
我想要的只是一个简单的翻转来改变类!我尝试的每件事要么不一致地打开或关闭类(class)。我一直试图满足的唯一其他要求是让监听器存在于函数中而不是内联。这就是使这成为不可能的原因吗?
function highlight(_event){
$(this).addClass("Highlighted");
}
function unhighlight(_event){
$(this).delay(2000,function(){
$(this).removeClass("Highlighted");
});
}
$(document).ready(function () {
$(".Content").live('mouseenter',highlight);
$(".Content").live('mouseout',unhighlight);
});
编辑
添加 .stop(true,true)
似乎很有帮助。
最佳答案
如果你想使用 live,你可以使用 .toggleClass()
执行以下操作, .mouseover()
& .mouseout()
:
$(".content").live("mouseover mouseout", function() {
$(this).toggleClass("highlight");
});
查看 demo here
更新:我不能离开这个,所以继续搞乱你的例子 - 在评论之后你在其他地方使用这些功能。所以这是我发现的:
而不是调用 .mouseout()
使用 .mouseleave()
- 出于某种原因 .mouseout()
当鼠标四处移动时 get 会被多次调用 - 它甚至会在鼠标第一次进入对象时被调用......请参阅最后的演示以了解我的意思
其次,.delay()
在这里并没有真正被正确使用——它实际上是为了排队效果——但你真正想要的是添加一个延迟函数(尽管这是你想要的效果) 所以改用 .setTimeout()
为您打电话。
The
.delay()
method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay —.delay()
is not a replacement for JavaScript's native.setTimeout()
function, which may be more appropriate for certain use cases.
所以完成的函数看起来像这样:
function highlight(_event) {
$(this).addClass("Highlighted");
}
function unhighlight(_event) {
var obj = $(this);
setTimeout(function() {
obj.removeClass("Highlighted");
}, 2000);
}
$(document).ready(function() {
$(".Content").live('mouseenter', highlight);
$(".Content").live('mouseleave', unhighlight);
});
参见 demo here 这个会告诉你我对 .mouseout()
的意思事件被多次触发,其中 .mouseleave()
函数仅在鼠标实际离开时调用一次。
注意:使用您的输入按钮按下警报确定,不要移动您的鼠标!!
参见 demo here在此处查看尽可能接近原始版本的最终版本。
关于jquery - 时髦的 mouseenter/mouseout 与 Jquery.live,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5364790/