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

如何在:focus状态下隐藏::after伪元素生成的文本内容?

错误原因

  1. 伪类和伪元素的书写顺序错误:CSS规范要求伪类必须放在伪元素之前,::after:focus属于不被浏览器识别的非法写法,正确的顺序应该是:focus::after
  2. 焦点状态的触发对象错误:form元素本身不会获得焦点,只有内部的可交互输入框<input>才会触发:focus状态,所以你无法通过监听form自身的焦点来控制伪元素显隐。

解决方法

你只需要删除原来错误的.form-search:after:focus规则,替换为以下写法即可:
使用CSS :focus-within伪类,只要form内部存在获得焦点的元素,就会匹配到form本身,直接控制其伪元素隐藏,该伪类兼容所有主流现代浏览器,是最稳妥的实现方案:

.form-search:focus-within::after {
  display: none;
}

完整修改后的CSS代码

.form-search__input:not(:focus) {
  color: transparent !important;
}
.form-search__input {
  font-weight: 600;
  font-size: 18px;
  color: #abff00;
  font-style: italic;
  font-family: "Open Sans";
}
.search-txt {
  position: absolute;
  left: 3rem;
  font-weight: 600;
  font-size: 18px;
  color: #abff00;
  font-style: italic;
  font-family: "Open Sans";
}
.form-search::after{
  content: "Search";
  font-weight: 600;
  font-size: 18px;
  color: #abff00;
  font-style: italic;
  font-family: "Open Sans";
  position: absolute;
  left: 3rem;
}
/* 新增正确规则,替换原来错误的.form-search:after:focus规则 */
.form-search:focus-within::after {
  display: none;
}

修改后输入框聚焦时,::after生成的Search文本就会自动隐藏,不会和输入内容重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:03