我有一个 div
并希望在我点击外部时隐藏它。我的代码是:
<div id="mydiv">The div must be above button</div>
$('#mydiv').click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$('#mydiv').fadeOut(300);
});
但它对我不起作用......
更新
完整代码如下。当我点击一个按钮时,它会在上面显示一个 div
,所以我需要在我点击外部时隐藏这个 div
。
<div id="but" style="text-align: right;"><button type="button">Show Div!</button></div>
<div id="mydiv" style="display:none;">The div must be above button</div>
$("#but button").click(function(){
var pos = $(this).offset(),
div = $("#mydiv");
// Make it visible off-page so
// we can measure it
div.css({
"display": "block",
"border": "1px solid black",
"position": "absolute",
"left": -10000,
"top": 0
});
// Move it where we want it to be
div.css({
"left": pos.left - 40,
"top": pos.top - div.height() - 10
});
});
$('#myDiv').click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$('#mydiv').fadeOut(300);
});
最佳答案
在 javascript 中,click 是一个 bubbling event ,它从一个 div 开始,然后上升到一个 document。当您使用 stopPropagation()
函数停止事件传播时,不会处理对文档的点击。因此,要解决您的问题,只需删除 e.stopPropagation()
。
最好的办法是:
$('#mydiv').click(function(e) {
e.stopPropagation();
$(this).fadeOut(300);
});
If I click on this div, how to make to click outside and hide this div ?
好吧,让我们想象一下,当您单击 ID 为“wrapperId”的容器时,“myDiv”应该被隐藏:
$("#wrapperId").click(function(e){
$('#mydiv').fadeOut(300);
})
如果容器是文档,您可以使用 $(document)
而不是 $("#wrapperId")
。
It is not working look what is happening: jsbin.com/ilowij/7
您应该在单击按钮时停止单击事件传播。进行这些更改:
$("#but button").click(function(e){
e.stopPropagation();
...
}
关于jquery - 单击外部时如何隐藏 DIV 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13892375/