JavaScript lose focus
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
}
}
精彩评论