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

我的自动下划线脚本异常:Tobias Ahlin脚本无法作用于输入框

解决Input元素无法使用::before伪元素的问题

嘿,我完全懂你遇到的困扰——这其实是CSS里一个容易踩的小坑,跟元素类型有关!

为什么Input上的::before不生效?

<input>属于替换元素(Replaced Element),这类元素的内容是由浏览器本身渲染的(比如输入框的文本区域、按钮的默认样式),CSS的::before和::after伪元素根本不会被浏览器解析,这就是你在开发者工具里看不到它的原因。而<p>是普通的非替换元素,所以伪元素能正常工作。

两种可行的解决方案

方案1:用包装元素模拟伪元素效果

这是最贴近你原脚本逻辑的方法——给input套一个容器,把伪元素加在容器上,让容器的样式和input配合:

<!-- 给input加一个包装容器 -->
<div class="edit input-container">
  <input type="text" placeholder="请输入内容">
</div>
.edit .input-container {
  position: relative;
  display: inline-block; /* 让容器只适配input的宽度 */
}

.edit input {
  text-decoration: none;
  outline: none;
  border: none;
  font-size: 1.125rem;
  background: transparent; /* 透明背景,不遮挡容器的伪元素 */
  padding-bottom: 4px; /* 给下划线留出空间 */
}

/* 把原伪元素的样式移到容器上 */
.edit .input-container::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #000;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.15s ease;
}

/* 触发下划线动画的条件,比如聚焦或 hover */
.edit input:focus ~ .input-container::before,
.edit .input-container:hover::before {
  visibility: visible;
  transform: scaleX(1);
}

方案2:直接用Input的边框实现动画

如果不想加额外容器,可以直接利用input的border-bottom来做过渡效果:

.edit input {
  text-decoration: none;
  outline: none;
  border: none;
  font-size: 1.125rem;
  position: relative;
  border-bottom: 2px solid transparent; /* 初始透明边框 */
  transition: all 0.15s ease;
  transform-origin: left center; /* 从左侧开始缩放 */
}

.edit input:focus {
  border-bottom-color: #000;
  transform: scaleX(1);
}

小提示

如果想要完全复刻Tobias Ahlin那种从左到右的下划线缩放动画,方案1的包装容器方法会更灵活,因为伪元素的transform可以更精准地控制动画起点和过渡效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:50:58