jQuery mouseenter() 和 mouseleave() 函数重复工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23714242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery mouseenter() and mouseleave() functions work repeatedly
提问by Baris Demirel
I have a picture and a div. The div is hidden(display:none;). I want to show the div when mouse is over the picture and hide the div again when mouse is not over the picture. I use mouseenter() and mouseleave() events to do this but when moue is over the picture, both of the functions work repeatedly. Here is the code that I define functions:`
我有一张图片和一个 div。div 是隐藏的(显示:无;)。我想在鼠标悬停在图片上时显示 div,并在鼠标悬停在图片上时再次隐藏 div。我使用 mouseenter() 和 mouseleave() 事件来做到这一点,但是当 moue 在图片上时,这两个函数都会重复工作。这是我定义函数的代码:`
$("#pic").mouseenter(function(){
$("#checkin").slideDown();
});
$("#pic").mouseleave(function(){
$("#checkin").slideUp();
});
I also tried the hover method but the result is the same.
我也尝试了悬停方法,但结果是一样的。
$("#pic").hover(
function(){
$("#checkin").slideDown(200);
},
function(){
$("#checkin").slideUp(200);
}
);
What is the problem, I can't understand.
有什么问题,看不懂。
Update:Here is the HTML code
更新:这是 HTML 代码
<tr><td valign='top' class='checkinpic'><img src='img.png' id='pic' height='100%'></td></tr>
...
...
<div id='checkin'>
You are not going to any activity this week.
</div>
回答by Baris Demirel
I found the solution. When I changed the element that works with the mouseleave event, it worked:
我找到了解决方案。当我更改与 mouseleave 事件一起使用的元素时,它起作用了:
var block = false;
$("#pic").mouseenter(function(){
if(!block) {
block = true;
$("#toggleDiv").slideDown(400, function(){
block = false;
});
}
});
$("#pic").mouseleave(function(){
if(!block) {
block = true;
$("#toggleDiv").slideUp(400, function(){
block = false;
});
}
});
Thank you for your help.
感谢您的帮助。
Update:I noticed that giving both the picture and div a class and defining the mouseenter and mouseleave events of the class is a better solution.
更新:我注意到给图片和 div 一个类并定义类的 mouseenter 和 mouseleave 事件是一个更好的解决方案。
回答by Magistr_AVSH
May fix something like this:
可以解决这样的事情:
var block = false;
$("#pic").mouseenter(function(){
if(!block) {
block = true;
$("#toggleDiv").slideDown(400, function(){
block = false;
});
}
});
$("#pic").mouseleave(function(){
if(!block) {
block = true;
$("#toggleDiv").slideUp(400, function(){
block = false;
});
}
});
回答by Runny
Here is the solution edited from ur code, hope it will help full for u.
这是根据您的代码编辑的解决方案,希望它对您有帮助。
$("#pic").hover(function() {
$("#checkin").slideDown(200);
},
function() {
$("#checkin").slideUp(200);
});
click the link below to run the code
点击下面的链接运行代码