:read-write 仅匹配原生可编辑表单控件(input、textarea、select),不匹配 contenteditable 元素;div[contenteditable="true"]:read-write 永远无效,应改用 [contenteditable="true"]:focus 等属性选择器实现样式控制。

:read-write 不匹配 div[contenteditable="true"] —— 这是绝大多数人踩坑的起点。浏览器规范里明确把 :read-write 的作用域限制在原生可编辑表单控件(input、textarea、select),不包含任何 contenteditable 元素,无论它是否设为 "true"。
为什么 div[contenteditable] 不触发 :read-write
不是浏览器 bug,是标准行为。W3C 定义中,:read-write 只响应「元素是否具备内在文本编辑能力」,而 contenteditable 是通过 DOM 层模拟编辑行为,不属于该伪类管辖范围。即使你用 JS 动态设置 el.contentEditable = "true",样式也不会自动更新——CSS 无法监听这个属性变化。
-
input[type="text"]:read-write✅ 匹配未设readonly且未禁用的输入框 -
textarea:read-write✅ 同上,但注意textarea[readonly]会退出匹配 -
div[contenteditable="true"]:read-write❌ 永远不生效,所有主流浏览器一致 -
input:read-write:focus⚠️ Safari 直到 iOS 15.4+ 才支持:read-write,旧版直接忽略整条规则
给 contenteditable 元素加活跃边框的可靠写法
别绕弯子,直接用属性选择器 + :focus 组合,语义清晰、兼容性好、可控性强。
- 基础聚焦样式:
[contenteditable="true"]:focus{ border: 2px solid #007bff; outline: none; } - 排除只读状态:
[contenteditable="true"]:not([contenteditable="false"]):focus - 兼容老式写法(如 IE):可额外加
[contenteditable]:focus,但需注意它也会匹配contenteditable="plaintext-only"等非常规值 - 如果容器内嵌 input/textarea,想让整个区域获得焦点时统一高亮,用
:focus-within:.editor:focus-within{ border-color: #007bff; }
:read-write 和 :read-only 的实际边界在哪
这两个伪类只管「静态可写性」,和运行时状态无关。它们不响应 JS 修改 readOnly 属性、不感知 contenteditable 切换、也不处理表单验证逻辑。
-
input设了readonly属性 → 匹配:read-only,不匹配:read-write -
input设了disabled→ 既不匹配:read-only,也不匹配:read-write;要用:disabled -
input[type="range"]→ 多数浏览器认为它不可文本输入,归入:read-only,但行为不统一 -
div[contenteditable]→ 完全游离于这两个伪类之外,必须手动控制 class 或用属性选择器
真正容易被忽略的是:当你依赖 :read-write 做样式切换时,其实已经把交互逻辑耦合进 CSS;一旦需求变成「点击后才允许编辑」「权限变更后动态启停」,纯 CSS 就撑不住了——这时候得靠 JS 控制 class,再让样式跟着 class 走,而不是赌伪类能跟上状态变化。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











