我试图在单击链接后显示#subscribe-pop div,并在其外部的任何地方单击时将其隐藏。如果更改以下内容,则可以显示和隐藏它:
$('document').click(function() {
TO
$('#SomeOtherRandomDiv').click(function() {
HTML:
<div id="footleft">
<a href="#" onclick="toggle_visibility('subscribe-pop');">Click here to show div</a>
<div id="subscribe-pop"><p>my content</p></div>
</div>
脚本:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById("subscribe-pop");
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
}
$('document').click(function() {
$('#subscribe-pop').hide(); //Hide the menus if visible
});
$('#subscribe-pop').click(function(e){
e.stopPropagation();
});
</script>
您必须停止事件在容器中的传播(在这种情况下为'footleft',因此父元素不会注意到事件已触发。
类似这样的东西:
HTML
<div id="footleft">
<a href="#" id='link'>Click here to show div</a>
<div id="subscribe-pop"><p>my content</p></div>
</div>
JS
$('html').click(function() {
$('#subscribe-pop').hide();
})
$('#footleft').click(function(e){
e.stopPropagation();
});
$('#link').click(function(e) {
$('#subscribe-pop').toggle();
});
看到它正在运行here。
将$(document).click()
更改为$('html').click()
将解决主要问题。
第二,您根本不需要toggle_visibility()
功能,只需执行以下操作:
$('#subscribe-pop').toggle();
参考:根据此答案将body
更改为html
:How do I detect a click outside an element?