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

Angular实现输入框获焦时打开搜索栏下方固定模态视图

实现JIRA风格搜索框下方模态视图

步骤1:调整HTML结构

在搜索容器内添加模态视图容器,基于父容器定位更精准:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="height: 50px;">
    <div class="container-fluid">
        <div class="search-bar-container">
            <input id="search" name="search" type="text" placeholder="Search..." class="search-bar form-control" />
            <!-- 搜索模态视图容器 -->
            <div id="search-modal" class="search-modal">
                <!-- 这里填充搜索内容,比如建议列表、筛选器等 -->
                <div class="modal-inner">
                    搜索面板内容区
                </div>
            </div>
        </div>
    </div>
</nav>

步骤2:编写CSS样式

控制模态视图的尺寸、定位和显示状态:

/* 父容器设为相对定位,作为模态框的定位基准 */
.search-bar-container {
    position: relative;
}

/* 模态视图基础样式 */
.search-modal {
    position: absolute;
    top: 100%; /* 紧贴搜索框底部 */
    left: 0;
    width: 400px;
    height: 600px;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    z-index: 1000; /* 确保在导航栏上方 */
    display: none; /* 默认隐藏 */
}

/* 模态视图激活状态 */
.search-modal.active {
    display: block;
}

/* 消除搜索框默认边距,避免模态框和搜索框之间出现空隙 */
.search-bar {
    margin-bottom: 0;
}

步骤3:编写TS交互逻辑

处理搜索框的焦点事件,同时解决点击模态框时不自动关闭的问题:

const searchInput = document.getElementById('search') as HTMLInputElement;
const searchModal = document.getElementById('search-modal') as HTMLDivElement;

// 搜索框获焦时显示模态框
searchInput.addEventListener('focus', () => {
    searchModal.classList.add('active');
});

// 点击模态框内部时,阻止触发搜索框的失焦事件
searchModal.addEventListener('mousedown', (e) => {
    e.preventDefault();
});

// 搜索框失焦时延迟隐藏模态框,给点击模态框留响应时间
searchInput.addEventListener('blur', () => {
    setTimeout(() => {
        searchModal.classList.remove('active');
    }, 100);
});

补充优化

如果需要点击页面其他区域也关闭模态框,可以添加全局点击监听:

document.addEventListener('click', (e) => {
    const isClickInside = searchInput.contains(e.target as Node) || searchModal.contains(e.target as Node);
    if (!isClickInside) {
        searchModal.classList.remove('active');
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:07:23