我正在尝试创建一个小的 20x20px div 框,单击时会打开位于第一个框内的 200x200px 框:
HTML
<div id="container" style="width:20px; height:20px;">
<div id="box" style="display:none;width:200px; height:200px;">
<img src="example1.gif" />
<img src="example2.gif" />
</div>
</div>
瞄准
我的目标是当 #container
时做到这一点单击,#box
然后,用户将单击此框中的图像和 #box
然后就会淡出。
-
#container
单击并#box
fadeIn();
- 项目
#box
被点击 -
#box
fadeOut()
为此,我使用以下 jQuery:
$(document).on("click", "#container", function(){
$("#box").fadeIn("fast");
});
$(document).on("mouseleave", "#box", function(){
$("#box").fadeOut("fast");
});
$(document).on("click", "#box img", function(){
// Do things, removed for example
$("#box").fadeOut();
});
实际发生的情况
目前它不起作用,因为发生了这种情况:
- 点击
#container
-
#box
淡入 - 点击
#box img
- //做一些事情,例如移除
-
#box
淡出 -
#box
淡入
上面列表中的第 6 点不应发生,该框不应淡入。
我认为问题出在 .on("click", "#container", function(){
这可能会在 #container #box img
时应用该代码被点击了,我怎样才能阻止它?
演示
最佳答案
您需要使用event.stopPropagation() 。该事件正在冒泡,导致 div 再次淡入。
$(document).on("click", "#box img", function(e){
e.stopPropagation();
// Do things, removed for example
$("#box").fadeOut();
});
关于jQuery 在单击时执行,但不在子单击时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036308/