lon*_*day 11
我不喜欢使用的解决方案,stopPropagation因为我经常使用事件冒泡来管理各种链接.如果盒子存在,我不想担心他们可能会停止工作.我的选择看起来像这样:
var $box = $('#box');
$(document.body).click(function(){
if (!$box.has(this).length) { // if the click was not within $box
$box.hide();
}
});
Run Code Online (Sandbox Code Playgroud)
该has函数只过滤选择并返回元素,只要它们包含作为参数传递的元素(您也可以使用选择器字符串,但这里不相关).如果单击位于框外,length则0条件将通过,框将被隐藏.
这应该通过设置一个布尔值来优化盒子当前是否可见,并且只在当前可见的情况下进行has调用.
像这样:
$("#thediv").show(0, function() {
var that = $(this);
$(document).bind("click", function(e) {
if($(e.target).attr("id") != that.attr("id")) {
that.hide();
$(this).unbind("click");
}
});
});
Run Code Online (Sandbox Code Playgroud)
在这里小提琴:http : //jsfiddle.net/XYbmE/3/
| 归档时间: |
|
| 查看次数: |
15946 次 |
| 最近记录: |