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

如何修改input[type=time]中选中数字的高亮颜色?

修改input[type=time]选中数字的高亮颜色

问题说明

我已经能用这段CSS成功修改普通文本的选中高亮颜色:

::selection {
  background: #e4d2ba;
}

自定义文本选中颜色效果

但input[type=time]组件里选中数字的高亮颜色还是默认样式,试了下面的代码完全没用:

input::selection {
  background: #e4d2ba;
}
input[type=time]::selection {
  background: #e4d2ba;
}

时间输入框数字仍为默认选中颜色

补充:之前看过一个包含大量时间输入框样式的讨论帖,但里面完全没提选中颜色的修改方法。

可行方案

原生input[type=time]的内部元素被浏览器深度封装,常规::selection伪元素无法穿透控制,目前有两种可行思路:

1. WebKit内核浏览器专属方案

Chrome、Edge、Safari等WebKit系浏览器提供了特定伪元素,可控制时间输入框的内部字段样式,包括选中状态:

/* 先设置时间输入框各部分的基础样式 */
input[type=time]::-webkit-datetime-edit-text,
input[type=time]::-webkit-datetime-edit-hour-field,
input[type=time]::-webkit-datetime-edit-minute-field,
input[type=time]::-webkit-datetime-edit-second-field {
  color: #333;
}

/* 针对选中的时间字段设置高亮 */
input[type=time]:focus::-webkit-datetime-edit-hour-field:focus,
input[type=time]:focus::-webkit-datetime-edit-minute-field:focus,
input[type=time]:focus::-webkit-datetime-edit-second-field:focus {
  background-color: #e4d2ba;
  color: #000;
}

注意:这个方案仅对WebKit内核浏览器生效,Firefox和旧版Edge不支持。

2. 自定义时间输入组件(跨浏览器兼容)

要实现全浏览器一致的效果,最稳妥的方式是放弃原生控件,自己用HTML+CSS+JS搭一个时间输入组件,完全掌控所有样式:

<div class="custom-time-input">
  <input type="number" class="time-segment" min="0" max="23" placeholder="HH">
  <span>:</span>
  <input type="number" class="time-segment" min="0" max="59" placeholder="MM">
</div>

然后给自定义组件设置选中样式:

.custom-time-input .time-segment::selection {
  background: #e4d2ba;
}

最后用JS补充时间格式验证、上下箭头调整数值等功能,就能实现和原生控件类似的交互,同时选中高亮样式完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:17:32