我有一个浮动的div,当它被显示时,我希望在用户点击div以外的区域时将其隐藏。类似于.hover()函数在悬停在元素上时的回调,只不过我想使用点击事件。
我尝试在body上设置点击事件来隐藏div,但结果出乎意料。
有人有想法如何轻松实现这个功能吗?
我尝试在body上设置点击事件来隐藏div,但结果出乎意料。
有人有想法如何轻松实现这个功能吗?
我在一个论坛上找到了解决方案...但是我找不到原始作者来给予功劳。
这是修改后的版本(存在于我的代码中)。
$(document).bind('mousedown.yourstuff', function(e) {
var clicked=$(e.target); // get the element clicked
if( clicked.is('#yourstuff')
|| clicked.parents().is('#yourstuff')) {
// click safe!
} else {
// outside click
closeIt();
}
});
function closeIt() {
$(document).unbind('mousedown.emailSignin');
//...
}
我还有ESC键绑定和一个未在上面显示的“关闭”HTML锚点。
var div_active, the_div;
the_div = $("#the-div");
div_active = false;
$("#show-the-div-button").click(function() {
if (div_active) {
the_div.fadeOut(function(){
div_active = false;
});
} else {
the_div.fadeIn(function(){
div_active = true;
});
}
});
$("body").click(function() {
if div_active {
the_div.fadeOut();
div_active = false;
}
});
the_div.click(function() {
return false;
});
对我来说,在文档上使用事件处理程序效果很好:
function popUp( element ) { element.onmousedown = function (event) { event.stopPropagation(); }; document.onmousedown = function () { popDown( element ); };
document.body.appendChild( element ); }
function popDown( element ) { document.body.removeChild( element );
document.onmousedown = null; }