这个问题已经被问多次,但是没有一个答案似乎为我工作。
在div的CSS如下:
#info{
display: none;
position: fixed;
z-index: 500;
height: 50%;
width: 60%;
overflow: auto;
background: rgba(187, 187, 187, .8);
}
我试着用下面的代码:
$("#info").click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$("#info").hide();
});
还有这样的代码:
$(document).mouseup(function (e){
var container = $("#info");
if (container.has(e.target).length === 0) {
container.hide();
}
});
然而,每当我点击它也消失的股利,不知道为什么,但它确实。
任何其他的事情可能的工作?
当你的目标有id=info
,所以你可以尝试:
$(document).click(function(e) {
// check that your clicked
// element has no id=info
if( e.target.id != 'info') {
$("#info").hide();
}
});
您也可以尝试:
$(document).click(function() {
if( this.id != 'info') {
$("#info").hide();
}
});
据发表评论
$(document).click(function(e) {
// check that your clicked
// element has no id=info
// and is not child of info
if (e.target.id != 'info' && !$('#info').find(e.target).length) {
$("#info").hide();
}
});
附加的onclick
事件处理程序document
对象:
$(document).click(function(e) {
if(e.target.id != 'info') {
$("#info").hide();
}
});
演示: http://jsfiddle.net/aUjRG/
这里是纯JavaScript的解决方案,以帮助您更好地了解它的发生:
function hideInfo(){
if(window.event.srcElement.id != 'info'){
document.getElementById('info').style.display = 'none';
}
}
document.onclick = hideInfo;
演示: http://jsfiddle.net/mmzc8/
这两种解决方案会检查用户点击的地方是用的ID的元素info
。 假设用户没有点击的info
元素,然后隐藏info
元素。
为确保您有过在iPad上有效的解决方案,那么你需要使用下面的函数,而不是触发:
$(document).on("mousedown touchstart",function(e){
var $info = $('#info');
if (!$info.is(e.target) && $info.has(e.target).length === 0) {
$info.hide();
}
});
同样,如果你正在寻找盖掉鼠标松开,加上“touchend”:
$(document).on("mouseup touchend",function(e){
...
});
试试这个代码,这是最适合我。
jQuery('.button_show_container').click(function(e) {
jQuery('.container').slideToggle('fast');
e.stopPropagation();
});
jQuery(document).click(function() {
jQuery('.container').slideUp('fast');
});
您可以在鼠标仅选中添加类单击div元素内的特定格或任何用户点击与否。
$(document).click(function(e){
if ( !$(e.target).hasClass("[class name for check]") &&
$("[element class or id]").css("display")=="block" ) {
//...code if clicked out side div
}
});
尝试以下解决方案。 它甚至工作递归:
$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});
参考- https://stackoverflow.com/a/7385673/3910232