Show div once clicked and hide when clicking outsi

2019-04-10 11:10发布

问题:

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>

回答1:

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.



回答2:

I reckon that the asker is trying to accomplish a jquery modal type of display of a div.

Should you like to check this link out, the page upon load displays a modal div that drives your eye into the center of the screen because it dims the background.

Moreover, I compiled a short jsFiddle for you to check on. if you are allowed to use jquery with your requirements, you can also check out their site.

Here is the code for showing or hiding your pop-up div

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


回答3:

Changing $(document).click() to $('html').click() should solve the main problem.

Secondly, you do not need the toggle_visibility() function at all, you can simply do:

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

Ref: changed body to html as per this answer: How do I detect a click outside an element?