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

鼠标悬停搜索输入框时显示搜索历史div失效问题求助

问题原因与解决方案

你的CSS选择器失效的核心原因是相邻兄弟选择器+的作用范围限制:

  • +只能选中直接紧跟在目标元素之后的同级元素
  • 你的.search-bar-input在<form>标签内部,而.search-history是<form>的同级元素,和input并不直接相邻,所以.search-bar-input:hover + .search-history无法匹配到目标元素。

修复方案(两种可选)

方案1:监听父容器的hover(推荐)

给父元素.search-bar添加hover状态,只要鼠标在搜索栏容器内(包括输入框和历史记录),就显示历史记录,避免鼠标移到历史记录上时突然消失的问题:

<div class="search-bar">
    <form class="search-form" autocomplete="off">
        <input type="text" class="search-bar-input" name="search-request" placeholder="Type here..." required minlength="4" maxlength="32">
    </form>
    <div class="search-history">
        search history
    </div>
</div>
.search-bar-input
{
    text-align: center;
    height: 50px;
    width: 150px;
    margin: auto;
}

.search-bar-input:hover
{
    border: solid 2px lightgrey;
    outline: none;
}

.search-history
{
    display: none;
    height: 50px;
    width: 150px;
    background-color: rgb(226, 226, 226);
    margin: auto; /* 让历史记录和输入框对齐 */
}

/* 修改这里:监听父容器的hover状态 */
.search-bar:hover .search-history
{
    display: block;
}

方案2:监听form的hover

如果只想在鼠标悬停输入框(即form区域)时显示历史记录,可以利用form和search-history的相邻兄弟关系:

/* 替换原来的.search-bar-input:hover + .search-history */
.search-form:hover + .search-history
{
    display: block;
}

/* 同时保留历史记录自身的hover,防止移上去消失 */
.search-history:hover
{
    display: block;
}

关键知识点补充

  • 相邻兄弟选择器A + B:仅匹配紧跟在A元素之后的同级B元素
  • 后代选择器A B:匹配A元素内部的所有B元素
  • 父容器hover的方式更符合用户体验,因为用户查看历史记录时鼠标会离开输入框,此时历史记录不会突然隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:01:59