Hide a div when clicked outside of it(在外部单击时隐藏 div)
问题描述
这个问题已被问过多次,但似乎没有一个答案对我有用.
This question has been asked multiple times, however none of the answers seem to work for me.
div的css如下:
#info{
display: none;
position: fixed;
z-index: 500;
height: 50%;
width: 60%;
overflow: auto;
background: rgba(187, 187, 187, .8);
}
我尝试使用以下代码:
$("#info").click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$("#info").hide();
});
还有这段代码:
$(document).mouseup(function (e){
var container = $("#info");
if (container.has(e.target).length === 0) {
container.hide();
}
});
然而,每当我点击 div 时,它也会消失,不知道为什么,但确实如此.
还有什么可能有用的吗?
Yet whenever i click on the div it also disappears, no clue why but it does.
Any thing else that might work?
推荐答案
由于你的target有id=info,所以你可以试试:
As your target has id=info, so you can try:
$(document).click(function(e) {
// check that your clicked
// element has no id=info
if( e.target.id != 'info') {
$("#info").hide();
}
});
你也可以试试:
$(document).click(function() {
if( this.id != 'info') {
$("#info").hide();
}
});
根据评论
$(document).click(function(e) {
// check that your clicked
// element has no id=info
// and is not child of info
if (e.target.id != 'info' && !$('#info').find(e.target).length) {
$("#info").hide();
}
});
这篇关于在外部单击时隐藏 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在外部单击时隐藏 div
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
