单击时显示div,单击时隐藏 [英] Show div once clicked and hide when clicking outside

查看:132
本文介绍了单击时显示div,单击时隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在点击链接后显示#subscribe-pop div,并在点击任何位置时隐藏它。我可以让它显示并隐藏,如果我改变:

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

TO

  $('#SomeOtherRandomDiv')。click(function(){

HTML:

 < div id =footleft> 
< a href =#onclick =toggle_visibility( 'subscribe-pop');>点击此处显示div< / a>
< div id =subscribe-pop>< p>我的内容< / p>< / div>
< / div>

脚本:

 < script type =text / javascript> 
function toggle_visibility(id){
var e = document.getElementById(subscribe- );
if(e.style.display =='block')
e.style.display ='none';
else
e.style.display = 'block';
}
}

$('document')。click(function(){
$('#subs cribe-pop')。hide(); //隐藏菜单如果可见
});

$('#subscribe-pop')。click(function(e){
e.stopPropagation();
});
< / script>


解决方案

您必须停止容器中的事件传播在这种情况下,'footleft'),所以父元素不会注意到事件被触发。



类似这样的:



HTML

 < div id =footleft> 
< a href =#id ='link'>点击此处显示div< / a>
< div id =subscribe-pop>< p>我的内容< / p>< / div>
< / div>

JS
< $($'$')$('html')。click(function(){
$('#subscribe-pop')。hide();
})

$('#footleft')。click(function(e){
e.stopPropagation();
});
$ b $('#link')。click(function(e){
$('#subscribe-pop')。toggle();
});

查看工作情况 这里


I'm trying to show the #subscribe-pop div once a link is clicked and hide it when clicking anywhere outside it. I can get it to show and hide if I change the:

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

<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>

解决方案

You have to stop the event propagation in your container ('footleft' in this case), so the parent element don't notice the event was triggered.

Something like this:

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();
 });

See it working here.

这篇关于单击时显示div,单击时隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆