【问题标题】:Show div once clicked and hide when clicking outside单击时显示 div,单击外部时隐藏
【发布时间】:2013-04-18 02:07:50
【问题描述】:

我试图在单击链接后显示#subscribe-pop div,并在单击链接之外的任何位置时隐藏它。如果我更改以下内容,我可以让它显示和隐藏:

$('document').click(function() {

$('#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>

【问题讨论】:

标签: javascript html hide show


【解决方案1】:

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

其次,你根本不需要toggle_visibility() 函数,你可以简单地这样做:

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

参考:根据此答案将body 更改为htmlHow do I detect a click outside an element?

【讨论】:

    【解决方案2】:

    您必须停止容器中的事件传播(在本例中为“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

    【讨论】:

    • 太棒了,这很好用,感谢您(和其他所有人)的回复:)
    • 了解,但仍然在我身边工作,即使使用表单。 Try it。另外,请确保您的 html 是有序的。如果可行,请不要忘记检查此答案作为解决方案。 :)
    • 可爱的解决方案,我正在寻找这个
    【解决方案3】:

    我认为提问者正在尝试完成 div 的 jquery 模态类型显示。

    如果您想检查一下这个link,加载页面时会显示一个模态 div,因为它会使背景变暗,从而将您的眼睛吸引到屏幕中心。

    此外,我整理了一个简短的jsFiddle 供您查看。如果您被允许根据您的要求使用 jquery,您也可以查看他们的网站。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      相关资源
      最近更新 更多