CSS background-color属性用于设置元素背景色,覆盖内容、内边距和边框区域但不含外边距;支持颜色名、十六进制、rgb等值,transparent为默认值;IE8及以下不支持inherit。

直接用 CSS 设置 background-color 就生效
绝大多数场景下,给 input 设背景色不需要 JS,纯 CSS 最干净。只要没被更高优先级样式(比如浏览器自动填充)覆盖,background-color 就能立刻起效。
常见写法:
input[type="text"] {
background-color: #f5f5f5;
color: #333;
}
注意两点:
- 如果 input 有
border或outline,建议同步调整,避免视觉割裂 - 深色背景配浅色文字时,务必检查 WCAG 对比度(至少 4.5:1),否则影响可访问性
JavaScript 动态改 background-color 的正确写法
用 JS 改背景色,核心是操作 DOM 元素的 style.backgroundColor 属性,不是 style.background,也不是 jQuery 的 .style() 写法(那是错的)。
立即学习“前端免费学习笔记(深入)”;
错误示例:$("#aa").style.backgroundColor = 'red' —— $("#aa") 是 jQuery 对象,没有 style 属性
正确方式(原生):
const input = document.querySelector('input');
input.style.backgroundColor = '#e0f7fa';
正确方式(jQuery):
$('#aa').css('background-color', '#e0f7fa');
常用触发时机:
- 聚焦时:
input.addEventListener('focus', () => { input.style.backgroundColor = '...'; }) - 输入时:
input.addEventListener('input', () => { ... }) - 校验失败后:
if (!isValid) input.style.backgroundColor = '#ffebee';
Chrome 自动填充导致背景变黄,怎么真正覆盖
Chrome 在自动填充用户名、密码等字段后,会强加 input:-webkit-autofill 样式,背景固定为 #ffeb3b,普通 background-color 完全无效。
靠谱解法只有一条:
input:-webkit-autofill {
box-shadow: 0 0 0 1000px #ffffff inset !important;
-webkit-box-shadow: 0 0 0 1000px #ffffff inset !important;
}
关键点:
- 必须带
!important,否则不生效 - 用
box-shadow: inset而不是background,因为它是层叠在 autofill 底层之上的“盖子” -
#ffffff换成你实际需要的背景色;别用rgba(),Chrome 渲染不稳定 - 如果 input 原本有背景图,这个方案会遮住图片——此时只能禁用 autocomplete 或换 contenteditable 方案
input[type="color"] 选色后怎么实时更新页面背景
这个 type 的 value 不是“随便传个颜色就能用”,它极度挑剔格式:必须是小写、无空格、6 位十六进制,如 #ff6b35。传 #abc、rgb(255,0,0) 或带 alpha 的值,都会静默变成 #000000。
安全做法:
- 初始化时显式写全:
<input type="color" value="#ff6b35"> - 监听
input事件(不是change),才能拖拽实时响应 - 标准化 value 值:
colorInput.value.toLowerCase().replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`) - 兼容性检测必须手动:
const isColorSupported = document.createElement('input').type === 'color';,不支持就降级为带正则校验的文本框
最易忽略的一点:iOS Safari 15.4+ 虽支持 type="color",但默认点击热区极小,不加 <label> 包裹或 padding 扩展,用户根本点不中。



















