Hiding a layer when clicking anywhere on page except the layer

后端 未结 4 1772
孤独总比滥情好
孤独总比滥情好 2021-01-29 01:35
$(\'body\').click(function() {
//hide layer code here
});

This will hide the layer.

But I don\'t want the layer to be hidden when I click insid

相关标签:
4条回答
  • 2021-01-29 01:54
    $('body').click(function(ev){
        if(ev.target.className == 'yourLayerClass') {
            // Your code here
        }
    });
    
    0 讨论(0)
  • 2021-01-29 01:55

    I think the more elegant way is this:

    $('body').click(function(event) {
    // hide layer code here
    });
    $('#layer').click(function(event) {
    event.stopPropagation();
    });
    
    0 讨论(0)
  • 2021-01-29 02:11

    You can try something like this.

    $(document).ready(function () { 
                $('body').click(function(e) {
                    if(e.target.id !== 'layer') {
                        alert('Put code to hide layer here');
                    }
    
                });
            });
        </script>
    
    
    <body>
    <p id='layer'>This is layer</p>
    <p id='other'>This is other part </p>
    </body>
    

    Demo

    Also, you can create an overlay (the standard way)

    HTML

    <body>
    <div id='overlay'></div>
    <p id='layer'>This is layer</p>
    </body>
    

    JS

    $('#overlay').click(function(e) {
        alert('code to hide your layer'); 
        // Notice that this function won run when you click on layer but will run whenever you on any other part of body.
    });​
    

    Demo

    0 讨论(0)
  • 2021-01-29 02:16

    get the id to layer. for example: #layer

    and put this code to your script file:

    $('#layer').on('click', function (event) {
    event.stopPropagation();
    });
    
    0 讨论(0)
提交回复
热议问题