2010-06-19 22 views
1

我有一个搜索输入框,在翻转按钮时出现。我希望能够点击页面上的任何位置来重新隐藏搜索,而不是拥有自己的关闭按钮。jQuery - 单击(几乎!)任意位置以隐藏div

如果我附加一个点击处理程序的文件这工作正常,但问题是搜索本身是文件的一部分。因此,如果您单击输入(当然,您需要执行以输入搜索),搜索功能将消失。

我希望我能够写一个函数soemthing这样的...

$(document).not("#search").click(function(){ 
$('#search_holder').fadeOut('fast'); 
}); 

即从搜索应用单击处理整个文档分开。不幸的是,这是行不通的。

所以最新的答案?

,请多关照

回答

3

从传播取消click事件,当它从你关心的按钮来源:

$("#search").click(function(event){ 
    event.stopPropagation(); 
}); 
+0

@Starx我看到的回答说:“10分钟前”,而尼克的是“回答11分钟前安德的反应”。为什么downvote安德? – 2010-06-19 02:10:03

+0

对不起,恩德,没有注意到时间 – Starx 2010-06-19 02:21:17

+0

太棒了,那有效。多谢你们。 – swisstony 2010-06-19 02:36:18

3

您可以通过冒泡停止click事件做,像这样:

$(document).click(function() { 
    $('#search_holder').fadeOut('fast'); 
}); 
$("#search").click(function(e) { 
    e.stopPropagation(); 
}); 

event.stopPropagation()防止泡沫从去任何更高,一路document触发.fadeOut(),无处不在其他(默认情况下)冒泡为document,导致淡出发生。

0
Try this Its working perfect for me. 

$(document).mouseup(function (e) 
{ 
    var searchcontainer = $("#search_container"); 

    if (!searchcontainer.is(e.target) // if the target of the click isn't the container... 
     && searchcontainer.has(e.target).length === 0) // ... nor a descendant of the container 
    { 
     searchcontainer.hide(); 
    } 
}); 
+0

臃肿......其他答案是更好。 – 2013-08-11 07:11:37

相关问题