2013-04-24 217 views
4

我试图在单击链接时显示#subscribe-pop div,并在单击任何位置时隐藏它。我可以得到它的显示和隐藏,如果我改变:显示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> 
+2

http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – 2013-04-24 13:36:39

+0

使用'$(document)',而不是'$('document')' – Ian 2013-04-24 13:50:51

回答

12

你必须停止活动在你的容器中传播(在这种情况下是'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

+0

真棒,这很好,谢谢你(和其他人)的回复:) – rizzledon 2013-04-25 00:52:46

+0

理解,但仍然在我身边工作,即使形成。 [试试看](http://jsfiddle.net/4yBGt/2/)。另外,确保你的html是有序的。如果这样做,不要忘记检查这个答案作为解决方案。 :) – 2013-04-25 12:05:24

+0

谢谢你,我的html被搞砸了.. – rizzledon 2013-04-25 12:26:16

-1

更改$(document).click()$('html').click()应该解决是主要问题。

其次,你不需要toggle_visibility()功能可言,你可以简单地做:

$('#subscribe-pop').toggle(); 

编号:改变bodyhtml按照这样的回答:How do I detect a click outside an element?

1

我认为提问者试图完成一个div的jquery模式类型的显示。

如果您想检查此link,加载页面会显示一个模式div,将您的眼睛驱动到屏幕的中心,因为它会调暗背景。

此外,我编了一个短的jsFiddle供您检查。如果您可以按照您的要求使用jquery,那么您也可以查看他们的网站。

这里是代码显示或隐藏弹出的div

var toggleVisibility = function(){ 
    if($('#subscribe-pop').is(":not(:visible)")){ 
      $('#subscribe-pop').show(); 
     }else{ 
      $('#subscribe-pop').hide(); 
     } 
    }