【问题标题】:How can i prevent the search results div from closing when clicking inside of it单击内部时,如何防止搜索结果 div 关闭
【发布时间】:2020-04-12 07:58:42
【问题描述】:

我为这个问题做了一个 jsfiddle。 https://jsfiddle.net/1af4gyt5/

如果您在搜索输入中输入内容,您将看到搜索结果。我做了一个很重要的叠加层,如果我在搜索输入之外单击,叠加层将隐藏。如果我专注于它,它就会显示出来。但是,如果我在结果 DIV <a> LINK:aaaaaaa</a> etc. 内单击,我已经数小时试图使搜索结果 DIV 不关闭。

当我单击搜索结果 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>

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    您的问题出在您的 $('#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();
        }
    });
    

    【讨论】:

    • 感谢您的宝贵时间和回答。是的,我明白这一点,但是当用户在搜索输入之外单击时#show_search 不会隐藏,并且在#show_search 之外单击时不会隐藏。这就是我一直在努力解决的问题。
    猜你喜欢
    • 2017-08-14
    • 2023-04-10
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2021-09-01
    • 2016-02-10
    相关资源
    最近更新 更多