2016-06-10 202 views
0

对于我的显示/隐藏div,我只希望它在用户点击区域外或关闭按钮时关闭,无论您单击内部还是外部,它都会关闭,这也意味着你不能点击div内的链接。jQuery在外面点击显示/隐藏点击+按钮

$('#see').click(function(e){ 
$('.overlaybox').show("slide", { direction: "right" }, 500); 
    e.stopPropagation(); 
}); 

$(document).click(function(){ 
$('.overlaybox').hide("slide", { direction: "right" }, 500); 
}); 

jsfiddle

+1

http://stackoverflow.com/questions/11545518/hide-a-div-when-点击它之外引用此 –

回答

3

您需要检查点击的元素是否是目标元素与否。如果没有,你可以隐藏目标元素。否则跳过它。下面的代码将有助于

$(document).mouseup(function (e) 
 
    { 
 
    var container = $(".overlaybox"); 
 

 
    if (!container.is(e.target) && container.has(e.target).length === 0) 
 
    { 
 
     container.hide(); 
 
    } 
 
});
.overlaybox{ 
 
height:100px; 
 
    width:100px; 
 
    background:teal; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="overlaybox"> 
 
    </div>

这里是你的代码的更新小提琴 - https://jsfiddle.net/etmf4s2f/6/