开发者

JavaScript lose focus

开发者 https://www.devze.com 2023-01-12 17:50 出处:网络
I have a div that is set to display:inline using the onclick() JS event handler.How do I make the div go back to display:none when I click any where else on the page other than the now visible div?

I have a div that is set to display:inline using the onclick() JS event handler. How do I make the div go back to display:none when I click any where else on the page other than the now visible div?

I've Googled about 开发者_运维百科blur and setting the focus to another element but I don't know how to actually do it.


If you want to use jQuery, it is easy:

$('*').click(function(){
  if ($(this).attr('id') !== 'div_id'){
     $('#div_id').css('display', 'none');
  }
});

The above becomes rather slow with all * selector, So I would recommend you to use jQuery Outside Events plugin.

Example:

$('#div_id').bind('clickoutside', function(){
  $(this).css('display', 'none');
});


you can create an absolute div covering the whole window area by giving it 100% width and height and then give it an onclick to display:none your div. your div should have a z-index greater than the absolute div


the raw js sample can be find here.


document.onclick = function(e) {
  if (!e) var e = window.event;
  if (e.target.id == 'the_id_of_your_div') {
    // Do something
  } else {
    // Do something else
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消