jQuery和悬停功能上的奇怪行为 [英] JQuery and strange behavior on hover function
问题描述
我正在页面上所有具有class="box"
的DIV使用悬停效果:
I'm using a hover effect for all DIVs with class="box"
on a page:
JavaScript :
JQ(".box").hover(function() {
JQ(this).nextAll(".tooltip:first").css('visibility','visible');
});
JQ(".box").mouseleave(function(event) {
JQ(this).nextAll(".tooltip:first").css('visibility','hidden');
});
它在Firefox和Chrome中运行良好,但是在IE9和Opera中,当鼠标在.box DIV的边界内移动时,.tooltip
div消失并连续重新出现.
有什么想法为什么悬停函数会继续被DIV的每个像素调用?
It works fine in Firefox and Chrome but in IE9 and Opera the .tooltip
div disappears and re-appears continuously when the mouse moves within the boundaries of the .box DIV.
any ideas why the hover function keeps being called for every pixel of the DIV?
You can see a working version here
推荐答案
当您仅将一个函数传递给.hover()
时,当鼠标 两者 进入时,该函数将被调用和叶子.因此,您要使其在进入和离开时都可见,这与mouseleave处理程序冲突.
When you only pass one function to .hover()
that function is called when the mouse both enters and leaves. So, you're making it visible on both entering and leaving which is conflicting with your mouseleave handler.
您可以这样做:
JQ(".box").hover(function() {
JQ(this).nextAll(".tooltip:first").css('visibility','visible');
}, function() {
JQ(this).nextAll(".tooltip:first").css('visibility','hidden');
});
或者,多一点DRY(更少的重复代码):
Or, a little more DRY (less repeated code):
JQ.fn.nextTip = function(vis) {
return this.nextAll(".tooltip:first").css('visibility', vis);
}
JQ(".box").hover(function() {
JQ(this).nextTip('visible');
}, function() {
JQ(this).nextTip('hidden');
});
正在运行的演示: http://jsfiddle.net/jfriend00/DkgVg/
这篇关于jQuery和悬停功能上的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!