搜索框失焦后输入文本字号保持设置值的实现方案
问题:搜索框输入文本失焦后字号缩小,如何保持字号不变?
我正在开发一个搜索框,已经调整了文本字号等样式,但发现输入的文本在失焦后会缩小,无法保持输入时设置的字号。以下是我的HTML和CSS代码,请问如何实现文本字号保持不变?
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <section style="background-color: lightgrey;"> <input type="text" placeholder="Search Fennec Tech..." id="Search_Bar" onclick="Search()" class="Search-bar"> </section> </body> </html>
CSS代码
section { place-content: center; scroll-snap-align: start; block-size: 100vh; padding: 100px; font-family: sans-serif; font-size: 50px; } #Search_Bar { background-color: transparent; border: none; border-left: solid 5px blue; border-bottom: solid 5px blue; color: blue; } .Search-bar { height: 200px; width: 1250px; font-size: 20px; placeholder-text-color: red; } #Search_Bar:focus { animation-name: Search-anim; animation-duration: 2s; font-size: 75px; } @keyframes Search-anim { from { background-color: transparent; color: green; } to { background-color: white; color: blue; } } ::placeholder { color: red; font-size: 75px; opacity: 0.5; }
解决方案
问题根源是你仅在输入框聚焦状态(#Search_Bar:focus)设置了font-size:75px,失焦后输入框会继承.Search-bar类定义的font-size:20px,导致字号缩小。以下两种方法可以解决:
方法一:统一输入框的基础字号
将font-size:75px添加到#Search_Bar的基础样式中,让输入框无论是否聚焦,字号都保持一致:
#Search_Bar { background-color: transparent; border: none; border-left: solid 5px blue; border-bottom: solid 5px blue; color: blue; font-size: 75px; /* 添加此行,统一基础字号 */ } .Search-bar { height: 200px; width: 1250px; /* 移除或注释这里的font-size:20px,避免优先级冲突 */ placeholder-text-color: red; } #Search_Bar:focus { animation-name: Search-anim; animation-duration: 2s; /* 无需重复设置font-size,已由基础样式覆盖 */ }
方法二:仅在有内容时保持大字号
如果希望输入框为空且失焦时用小字号,有内容或聚焦时用大字号,可以借助:not(:placeholder-shown)伪类实现:
#Search_Bar:focus, #Search_Bar:not(:placeholder-shown) { font-size: 75px; }
这样输入框聚焦时、已有输入内容时字号为75px;空状态且失焦时,会回到.Search-bar定义的20px字号。
额外提示
- ID选择器优先级高于类选择器,
#Search_Bar的样式会覆盖.Search-bar,无需用!important强制覆盖,避免样式混乱。 placeholder-text-color是非标准属性,建议保留你已写的::placeholder伪类来设置占位符样式即可。
内容的提问来源于stack exchange,提问作者Daxton Taylor
相关产品推荐
相关产品推荐

