我有两个div,一个叠加在另一个之上。当我点击外部div时,我想隐藏内部div。当我点击内部Div时,内部div不会发生任何变化。同时,内部div中的链接应该工作得很好。如何使用jquery做到这一点?
<div class="outer">
<div class="inner"></div>
</div>
.outer {
background-color: #000;
position: fixed;
top: 0;
left: 0;
z-index: 9998;
height: 100%;
width: 100%;
opacity: 0.5;
}
.inner {
background-color: blue;
width: 240px;
position: fixed;
z-index: 9999;
left: 50%;
top: 50%;
margin-left: -300px;
margin-top: -150px;
}
未按预期工作的jQuery代码:
$('.outer').click(function(e){
$('.inner').hide();
});
$('.inner').click(function(e){
return false;
});
发布于 2012-12-26 19:46:09
这几乎总是通过防止冒泡来实现的。由于在.inner
上的任何点击都会冒泡到.outer
,我们需要防止这些点击:
$(".outer")
.on("click", function () {
$(this).find(".inner").slideUp();
})
.on("click", ".inner", function (event) {
event.stopPropagation();
});
小提琴:http://jsfiddle.net/22Uz7/
小提琴(使用你的CSS):http://jsfiddle.net/22Uz7/1/
您在下面的评论中指出您使用的是jQuery 1.4.2。因此,您将无法访问.on
方法-以下代码应该可以在1.4.2下运行:
$(".outer").bind("click", function () {
$(this).find(".inner").slideUp();
});
$(".inner").bind("click", function (event) {
event.stopPropagation();
});
发布于 2012-12-26 19:47:20
仅当目标类名称与outer
匹配时,才能使用event.target
指定操作
$('.outer').click(function(ev){
var target = ev.target;
if (target.className.match(/\bouter\b/)) {
$(this).find('.inner').toggle();
}
});
发布于 2012-12-26 19:44:35
做这样的事?
$('.outer').click(function(){
$('.inner').css('display', 'none');
});
还是为了它的孩子
$('.outer').click(function(){
$(this).find('.inner').css('display', 'none');
});
https://stackoverflow.com/questions/14045373
复制