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

实现搜索表单激活显示背景遮罩,点击外部关闭表单

实现搜索表单激活时的遮罩层交互效果

需求:当搜索表单处于激活状态时,页面背景生成遮罩层(仅搜索表单位于遮罩层之上);点击搜索表单外部或遮罩层时,表单关闭且遮罩层消失。

1. 调整HTML结构

先在页面中新增遮罩层元素,可放置在搜索表单同级位置或</body>标签前:

<form method="get" id="searchform" class="search-form" action="<?php echo esc_attr( home_url() ); ?>" _lpchecked="1">
    <fieldset>
        <input type="search" name="s" id="s" value="<?php the_search_query(); ?>" placeholder="<?php _e('Search the site', 'sociallyviral' ); ?>" <?php if (!empty($mts_options['mts_ajax_search'])) echo ' autocomplete="off" '; ?> />
        <button id="search-image" class="sbutton" type="submit" value="">
                <i class="fa fa-search"></i>
            </button>
    </fieldset>
</form>
<!-- 新增遮罩层 -->
<div id="search-overlay"></div>

2. 完善CSS样式

设置遮罩层默认隐藏状态,同时确保激活时表单层级高于遮罩:

/* 遮罩层基础样式 */
#search-overlay {
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    backdrop-filter: blur(5px);
    background: rgb(0 0 0 / 60%);
    z-index: 1;
    display: none; /* 默认隐藏 */
}

/* 搜索表单激活状态:确保在遮罩层上方 */
.search-form.active {
    z-index: 2;
    /* 可根据需求添加激活样式,比如边框高亮、位置调整等 */
}

/* 激活状态下显示遮罩层 */
#search-overlay.active {
    display: block;
}

3. 编写JavaScript交互逻辑

处理表单激活、关闭的触发事件,以及外部点击判断:

const searchForm = document.getElementById('searchform');
const searchOverlay = document.getElementById('search-overlay');
const searchInput = document.getElementById('s');
const searchButton = document.getElementById('search-image');

// 激活搜索表单
function activateSearch() {
    searchForm.classList.add('active');
    searchOverlay.classList.add('active');
    searchInput.focus(); // 自动聚焦输入框
}

// 关闭搜索表单
function deactivateSearch() {
    searchForm.classList.remove('active');
    searchOverlay.classList.remove('active');
    searchInput.blur();
}

// 点击搜索按钮触发激活(未激活时阻止默认提交)
searchButton.addEventListener('click', function(e) {
    if (!searchForm.classList.contains('active')) {
        e.preventDefault();
        activateSearch();
    }
});

// 点击遮罩层关闭表单
searchOverlay.addEventListener('click', deactivateSearch);

// 点击页面非表单区域关闭表单
document.addEventListener('click', function(e) {
    const isInForm = searchForm.contains(e.target);
    if (!isInForm && searchForm.classList.contains('active')) {
        deactivateSearch();
    }
});

// ESC键关闭表单
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && searchForm.classList.contains('active')) {
        deactivateSearch();
    }
});

功能说明

  • 遮罩层默认隐藏,仅在表单添加.active类时显示
  • 通过z-index层级控制,确保激活状态下表单始终在遮罩层之上
  • 支持多种关闭触发方式:点击遮罩、点击外部区域、按ESC键、提交表单(正常提交流程不受影响)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:33:18