简体   繁体   中英

how to close an element when click outside?

when i click on the button, the button toggle a specific class and opens something, this works, but the problem when i tried to type a code that will close that object when i click outside it, it doesn't work

 $(function() { $('button').on('click', function() { $('.list').toggle(); $('button').toggleClass('something'); }); $(document).on('click', function(e) { if (e.target !== 'list, button') { $('.list').hide(); } }); }); 
 .list { width: 100px; height: 150px; background: lightgray; display: none; } button { background: green } .something { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='list'></div> <button>button</button> 

That's because you have a CSS declaration of display: none . You'll also probably want to add some content to .list (so it can be hidden), as is done in the following example:

 $(function() { $(document).on('click', function(e) { if (e.target !== 'list, button') { $('.list').hide(); } }); }); 
 .list { width: 100px; height: 150px; background: lightgray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='list'>List</div> 

Hope this helps! :)

Try this code , here you will open the list and move over it but when you click outside of button and list , the list will be hidden :

 var change ="y"; $('button').on('click', function() { if(change == "y") { $(".list").show(); }}); $('button').on('blur', function() { if(change == "x") { $(".list").hide(); change="y";}}); $('.list').on('mouseover', function() { change="y";}); $('.list').on('mouseout', function() {change="x"; $('button').focus();}); 
 .list { width: 100px; height: 150px; background: lightgray; display: none; } button { background: green } .something { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div class='list'></div> <button>button</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM