:read-only

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020.

We’d love to hear your thoughts on the next set of proposals for the JavaScript language. You can find a description of the proposals here.
Please take two minutes to fill out our short survey.

:read-only CSS 伪类 表示元素不可被用户编辑的状态(如锁定的文本输入框)。

css
/* Selects any <input> element that is read-only */
/* Supported in Firefox with a prefix */
input:-moz-read-only {
  background-color: #ccc;
}

/* Supported in Blink/WebKit/Edge without a prefix */
input:read-only {
  background-color: #ccc;
}

备注: 这个选择器不只是选择具有 readonly 属性的<input> 元素,它也会选择所有的不能被用户编辑的元素。

语法

Error: could not find syntax for this item

示例

HTML

html
<input type="text" value="Type whatever you want here." />
<input type="text" value="This is a read-only field." readonly />
<p>This is a normal paragraph.</p>
<p contenteditable="true">You can edit this paragraph!</p>

CSS

css
input {
  min-width: 25em;
}
input:-moz-read-only {
  background: cyan;
}
input:read-only {
  background: cyan;
}

p:-moz-read-only {
  background: lightgray;
}
p:read-only {
  background: lightgray;
}
p[contenteditable="true"] {
  color: blue;
}

结果

规范

Specification
HTML
# selector-read-only
Selectors Level 4
# read-only-pseudo

浏览器兼容性

参见