CSS 伪类 :read-only 选择用户无法编辑的元素,如输入字段和文本区域。这包括具有 readonly 属性的元素。
语法
:read-only {
/* ... */
}
为了获得更好的浏览器兼容性,您可以使用 -moz 和 -webkit 前缀。例如:nput: -moz-read-only 和 input: -webkit-read-only。
CSS 伪类 :read-only - 基本示例
以下示例演示了如何使用 伪类 :read-only −
<html>
<head>
<style>
input:read-only {
background-color: pink;
border: 1px solid red;
}
</style>
</head>
<body>
<label for="readonlyInput">Read-only Input:</label>
<input type="text" id="readonlyInput" value="This is read-only" readonly>
<label for="editableInput">Editable Input:</label>
<input type="text" id="editableInput" value="This is editable">
</body>
</html>
CSS 伪类 :read-only - 确认表单信息
这是一个简单的预订确认表单示例,该表单向用户明确表示字段是只读的 -
<html>
<head>
<style>
.form-container {
width: 300px;
margin: 0 auto;
}
label {
display: block;
margin-top: 10px;
}
input:read-only {
background-color: pink;
border: none;
}
.submit-container {
margin-top: 10px;
}
button {
background-color: red;
border: none;
padding: 10px;
color: white;
}
</style>
</head>
<body>
<div class="form-container">
<h2>Form</h2>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="John Doe" readonly>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="john@example.com" readonly>
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="124569763" readonly>
<div class="submit-container">
<button type="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
CSS 伪类 :read-only- 为只读非表单控件设置样式
以下示例演示如何使用 伪类 :read-only,该伪类选择用户无法编辑的任何元素。
<html>
<head>
<style>
div.read-only-para {
background-color: pink;
border: 1px solid red;
}
div.editable-para {
background-color: violet;
border: 1px solid blue;
}
</style>
</head>
<body>
<div class="read-only-para">This is read-only div element</div><br>
<div class="editable-para" contenteditable>This is editable div element</div>
</body>
</html>