简体   繁体   English

如果单击外部,则使下拉菜单消失

[英]let dropdown menu disappear if I click outside

I have this search box search box 我有这个搜寻框搜寻框

And I've written a function to let the search box disappear when the user clicks outside or presses the Esc button. 我编写了一个函数,当用户单击外部或按Esc按钮时,搜索框消失。

The problem is, that when the user clicks on the search field, then search button "Suchen" in the menu does not disappear. 问题是,当用户单击搜索字段时,菜单中的搜索按钮“搜索”不会消失。

after search 搜索后

My code: 我的代码:

//Outside click
$("body").click(function(){
    jQuery('.searchfieldbox').fadeOut(500);
});
$("body").keydown(function(e){
    if(e.keyCode === 27 || e.which === 27 ){
        jQuery('.searchfieldbox').fadeOut(500);
    }
});
$(".pg-suche-lupe-button").click(function(e){
    e.stopPropagation();
});

How can solve this problem ??? 如何解决这个问题?

Try to make use of $(e.target).hasClass on the body click. 尝试在主体单击上使用$(e.target).hasClass

Stack Snippet 堆栈片段

 $("body").click(function(e) { if (!$(e.target).hasClass("searchfieldbox")) { jQuery('.searchfieldbox').fadeOut(500); } }); $("#input").click(function(e) { e.stopPropagation(); jQuery('.searchfieldbox').fadeIn(500); }); $("body").keydown(function(e) { if (e.keyCode === 27 || e.which === 27) { jQuery('.searchfieldbox').fadeOut(500); } }); 
 .searchfieldbox { height: 100px; background: #ccc; width: 100px; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input"> <div class="searchfieldbox"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM