我有一个
HTML div,我想在用户点击div之外的任何地方时隐藏它.点击哪个元素应该触发onclick事件?
解决方法
假设您使用的是最新的jQuery,v1.4.4:
$(<the div you want hidden>).click(false); //stop click event from bubbling up to the document $(document).one('click',function(){ $(<the div you want hidden>).hide(); //which will hide the div });
换句话说,如果你点击这个页面,这段代码会说’隐藏div,除非你点击div’.
Re:切换按钮
然后你会有类似的东西:
$('button').click(function(){ $('div').toggle(); }); $('div').click(false); $(document).click(function(){ $('div').hide(); //reset the toggle state,e.g. $('button').removeClass('selected'); });