You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击页面任意区域时关闭搜索框?

实现点击搜索图标切换搜索框+点击页面任意位置关闭搜索框

我已经实现了点击Font Awesome搜索图标来显示/隐藏搜索框的功能,现在想添加点击页面body区域任意位置时关闭搜索框的功能,以下是我的现有代码:

现有CSS代码

button.search-open {
    position: absolute;
    z-index: 999;
    background-color: transparent;
    border: none;
    padding: 8px 20px;
    font-size: 20px;
    color: #fff;
    top: 10px;
    margin-left: 1225px;
    border-radius: 4px;
    cursor: pointer;
}

现有HTML代码

<button class="search-open">
  <i class="fa fa-search" aria-hidden="true"></i>
  <i class="fa fa-times" aria-hidden="true"></i>
</button>
<div class="search-box">
  <form action="<?php echo home_url( '/' ); ?>">
    <h3>Type Here To Search</h3>
    <label>
      <input type="text" name="s" placeholder="Search...">
      <button type="submit" class="submit-btn"><i class="fa fa-search" aria-hidden="true"></i></button>
    </label>
  </form>
</div>

(注:原HTML里的fa-searchs是笔误,已修正为fa-search)

现有JS代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
        $(".search-open").click(function() {
            $('.search-box').toggle();
            $('.search-open .fa-search, .search-open .fa-times').toggle();
        });
  });
</script>

解决方案

要实现点击页面任意位置关闭搜索框,需要给document添加点击事件,同时阻止搜索按钮和搜索框内部的点击事件冒泡,避免误触发关闭逻辑。修改后的JS代码如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // 点击搜索按钮切换显示/隐藏
    $(".search-open").click(function(e) {
        // 阻止事件冒泡,避免触发document的点击事件
        e.stopPropagation();
        $('.search-box').toggle();
        $('.search-open .fa-search, .search-open .fa-times').toggle();
    });

    // 点击搜索框内部时,阻止事件冒泡
    $(".search-box").click(function(e) {
        e.stopPropagation();
    });

    // 点击document任意位置,关闭搜索框
    $(document).click(function() {
        if ($('.search-box').is(':visible')) {
            $('.search-box').hide();
            $('.search-open .fa-search').show();
            $('.search-open .fa-times').hide();
        }
    });
});
</script>

补充说明

  1. 如果搜索框默认需要隐藏,在CSS中添加:
.search-box {
    display: none;
}
  1. e.stopPropagation()的作用是阻止事件向上冒泡到document,这样点击搜索按钮或搜索框内部时,不会触发关闭逻辑。

内容的提问来源于stack exchange,提问作者El3magic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:06:46