DigitalOcean 为您的旅程每个阶段提供云产品。 立即开始使用 $200 免费积分!
:read-write
和 :read-only
选择器是两个可变伪类,旨在根据 disabled
、readonly
和 contenteditable
HTML 属性使表单样式更容易。 虽然浏览器支持并不差,但各种实现却相当古怪。
根据官方 CSS 规范,:read-write
选择器将在以下情况下匹配元素:
- 它是具有
readonly
或disabled
属性的input
。 - 它是没有
readonly
或disabled
属性的textarea
。 - 它是任何其他可编辑元素(由于
contenteditable
属性)。
语法和示例
/* Any element that is not writable */
:read-only { }
/* ... so you might want to scope it */
input:read-only,
textarea:read-only,
[contenteditable]:read-only {
cursor: not-allowed;
}
/* Any enabled text input
or enabled textarea
or element with the contenteditable attribute */
:read-write {
background: white;
cursor: text;
}
浏览器支持
这些浏览器支持数据来自 Caniuse,其中有更多详细信息。 数字表示浏览器从该版本开始支持该功能。
桌面
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
36 | 3* | 否 | 13 | 9 |
移动/平板电脑
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
127 | 127 | 127 | 9.0-9.2 |
规范中推荐的内容与浏览器实际执行的内容之间存在重大差异。 例如,如果我们坚持规范,每个用户可编辑但禁用的元素(disabled
或 readonly
)或根本不可编辑的元素都应由未限定的 :read-only
选择器进行定位。
Chrome | Firefox | Safari | Opera | |
---|---|---|---|---|
input | :read-write | :read-write | :read-write | :read-write |
input[disabled] | :read-write | :read-write | :read-write | :read-write |
input[readonly] | :read-only | :read-only | :read-only | :read-only |
[contenteditable] | — | :read-write | — | :read-only |
* | — | :read-only | — | :read-only |
同时,只有 Firefox 似乎执行了这样做,并且似乎也没有执行得很好,因为它将 disabled
输入视为 :read-write
。 关于 Opera 没有将 contenteditable
元素标记为 :read-write
,这仅仅是因为它不支持 contenteditable
。
优秀文章 Chris!
Microsoft Edge 现在也支持此功能(从版本 10547+ 开始):https://dev.windows.com/en-us/microsoft-edge/platform/status/?filter=f3f0000bf&search=mutability