如何让动态搜索结果悬浮于搜索栏下方(z-index设置无效)
搜索结果z-index无效的原因及修复方案
问题背景
你想要让搜索结果显示在搜索栏正下方,悬浮在页面内容之上,不挤压下方元素,但现在结果偏左还会把页面内容往下挤,设置z-index完全没效果。搜索结果容器id是companiesreturned,默认隐藏,搜索时用JS改成显示。
z-index无效的根本原因
- z-index只对非static定位的元素生效:你现在给搜索结果父容器加的
z-index:2没用,因为这个容器是默认的position:static,这种定位下z-index属性不生效,元素始终在正常文档流的层级里。 - 搜索结果容器处于正常文档流:没有脱离文档流的元素会占据页面空间,自然会挤压下方内容;而且它和搜索栏不在同一个定位上下文,没法对齐到搜索栏正下方。
修复方案(内联样式直接改)
1. 给搜索栏容器加相对定位
先把搜索栏所在的searchdiv改成相对定位,这样搜索结果可以基于它来定位:
<div id="searchdiv" style="display: inline; position: relative;"> <input style="display: inline; padding: 5px; border-radius: 10px;" id="inputsearch" name="searchcompany" type="text" placeholder="Enter ticker"> </div>
2. 重构搜索结果容器的定位与样式
把包裹companiesreturned的div改成绝对定位,脱离文档流,同时调整位置和层级:
<div style="position: absolute; z-index: 999; width: 100%; top: 100%; left: 0;"> <div class="bg-white rounded" style="display: block; margin-top: 5px; box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; height: 220px; overflow: auto; width: 100%; overflow-wrap: break-word;" id="companiesreturned"> <!-- 搜索结果列表保持不变 --> </div> </div>
position:absolute:让容器脱离正常文档流,不会再挤压下方内容top:100%; left:0:把容器对齐到搜索栏的底部左侧,刚好在正下方z-index:999:设个足够大的值,确保它能悬浮在其他内容上面(现在因为是绝对定位,这个属性才会生效)width:100%:让结果容器宽度和搜索栏一致,不会偏左
3. 调整结构层级
把上面改好的搜索结果容器移到searchdiv里面,这样才能基于搜索栏的相对定位来精准对齐:
<div id="searchdiv" style="display: inline; position: relative;"> <input style="display: inline; padding: 5px; border-radius: 10px;" id="inputsearch" name="searchcompany" type="text" placeholder="Enter ticker"> <!-- 把搜索结果容器放在这里 --> <div style="position: absolute; z-index: 999; width: 100%; top: 100%; left: 0; display: none;" id="search-results-wrapper"> <div class="bg-white rounded" style="box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; height: 220px; overflow: auto; width: 100%; overflow-wrap: break-word;" id="companiesreturned"> <ul style="list-style: none; padding-left: 0;" id="listofcompanies"> <!-- 列表项内容不变 --> </ul> </div> </div> </div>
提示:记得改JS逻辑,原来控制
companiesreturned显示隐藏的代码,改成控制外层的search-results-wrapper就行(或者直接控制companiesreturned,保持它默认display:none)。
内容的提问来源于stack exchange,提问作者trying
相关产品推荐
相关产品推荐

