我做了一个jsfiddle来回答这个问题。https://jsfiddle.net/1af4gyt5/
如果您在搜索输入中键入,那么您将看到搜索结果。我做了一个覆盖图,这一点很重要,如果我在搜索输入之外点击,覆盖图就会隐藏。如果我把焦点放在里面,它就会显示出来。但我已经尝试了几个小时,试图使搜索结果DIV不关闭,如果我点击结果DIV <a> LINK:aaaaaaa</a> etc.。
有人能帮我防止当我点击搜索结果DIV(#show_search)中的链接时关闭搜索结果DIV(#show_search)吗?我也希望它能结合搜索输入的叠加效果来工作。
非常感谢您的宝贵时间,非常感谢!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
#show_search{
width: 506px;
height: auto;
border: 2px solid black;
display: none;
position: absolute;
z-index:1;
}
#show_search a{
border-bottom: 1px solid #ddd;
display: block;
text-decoration: none;
color:black;
padding:10px;
text-align: center;
z-index:1;
background:yellow;
}
#search {
z-index:1;
}
#overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: -1;
cursor: default;
}
</style>
<div id="overlay"></div>
<form class="form-inline my-0"><div class="form-group has-search">
<span class="fa fa-search form-control-feedback"></span>
<input id='search' type="text" class="form-control input-more-width" placeholder="Search">
</div></form><div class="show_search" id="show_search"><a>LINK:aaaaaa</a><a>LINK:bbbbbbb</a><a>LINK:cccccccc</a></div>
<script>
$("#search").keyup(function(){
$("#show_search").show();
});
$('#search').focus(function() {
$("#overlay").show();
$("#search").keyup(function(){
$("#overlay").show();
$('#search').focusout(function() {
$(".show_search").hide();
$("#overlay").hide();
});
});
});
</script>发布于 2020-04-11 08:57:46
您的问题出在$('#search').focusout处理程序中,每当您单击#show_search中的链接(或执行任何操作以从搜索框中移除焦点)时,都会调用该处理程序,因为这包括
$(".show_search").hide();这会隐藏搜索结果框。
要使#show_search框在单击外部或#search输入外部时隐藏,请向整个页面添加一个click处理程序,并检查单击是否不在这些元素中;如果不在,请关闭#show_search框:
$(document).on('click', function (e) {
if ($(e.target).closest("#search").length === 0 && $(e.target).closest("#show_search").length === 0) {
$('#show_search').hide();
}
});https://stackoverflow.com/questions/61150521
复制相似问题