Jquery 在div外部单击时隐藏该div
这个问题已经被问了很多次,但是没有一个答案对我有效 该部门的css如下所示:Jquery 在div外部单击时隐藏该div,jquery,html,onclick,hide,Jquery,Html,Onclick,Hide,这个问题已经被问了很多次,但是没有一个答案对我有效 该部门的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();
#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时,它也会消失,不知道为什么,但它确实消失了。还有其他可能有用的吗 由于您的目标具有
id=info
,因此您可以尝试:
$(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();
}
});
据评论
将
onclick
事件处理程序附加到文档
对象:
$(document).click(function(e) {
if(e.target.id != 'info') {
$("#info").hide();
}
});
演示:
下面是一个纯JavaScript解决方案,可帮助您更好地了解它所发生的情况:
function hideInfo(){
if(window.event.srcElement.id != 'info'){
document.getElementById('info').style.display = 'none';
}
}
document.onclick = hideInfo;
演示:
两种解决方案都将检查用户单击的位置是否位于ID为
info
的元素上。假设用户没有单击info
元素,然后隐藏info
元素。为确保您的解决方案也适用于iPad,则您需要使用以下功能:
$(document).on("mousedown touchstart",function(e){
var $info = $('#info');
if (!$info.is(e.target) && $info.has(e.target).length === 0) {
$info.hide();
}
});
类似地,如果您希望覆盖鼠标,请添加“touchend”:
$(document).on("mouseup touchend",function(e){
...
});
试试这个代码,这对我来说是最好的
jQuery('.button_show_container').click(function(e) {
jQuery('.container').slideToggle('fast');
e.stopPropagation();
});
jQuery(document).click(function() {
jQuery('.container').slideUp('fast');
});
您只能添加一个类,以便在鼠标单击该特定div或该div元素中的任何元素时进行检查
$(document).click(function(e){
if ( !$(e.target).hasClass("[class name for check]") &&
$("[element class or id]").css("display")=="block" ) {
//...code if clicked out side div
}
});
尝试下面的解决方案。它甚至可以递归工作:
$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});
参考-一个问题很难回答(到目前为止效果很好),但是当你点击标签或文本时,它也会消失(逻辑)。这也有解决办法吗?@goey,即
h1
标记或info
div中的text
是的,如果现在单击text(纯文本或标记之间的文本),div也会隐藏。有没有办法让这个div的“children”也成为“donhide”函数的一部分?谢谢,更新后的代码可以很好地处理children元素。这是一个纯拷贝,没有任何引用。
$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});