在外部单击时隐藏div [英] Hide div when clicking outside
本文介绍了在外部单击时隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不仅搜索了Google,而且还在这里搜索,仍然必须找到一个可行的解决方案.
I've searched and search not only google but also here and still have to find a solution that will work.
我有一个默认情况下是隐藏的div,然后通过单击链接进行切换.当您在div之外单击时,我也希望它隐藏.我想很简单,但是我尝试过的任何方法都没有奏效.
I have a div that is hidden by default, then toggled by clicking on a link. I also want it to hide when you click outside of the div. Simple, I thought, but nothing I've tried had worked yet.
这是jquery:
<script type="text/javascript">
function toggleDiv(divID) {
$("#"+divID).fadeToggle(200);
}
</script>
以及切换它的链接:
<a onclick="toggleDiv('myDiv');">Link</a>
然后是div:
<div id="myDiv">
stuff
</div>
如果有人有任何建议,我将不胜感激.
If anyone has any advice, I would really appreciate it.
推荐答案
这应该为您解决问题:
var openDiv;
function toggleDiv(divID) {
$("#" + divID).fadeToggle(200, function() {
openDiv = $(this).is(':visible') ? divID : null;
});
}
$(document).click(function(e) {
if (!$(e.target).closest('#'+openDiv).length) {
toggleDiv(openDiv);
}
});
现在适用于所有情况.
Now works for all scenarios.
这篇关于在外部单击时隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文