动态伪类选择器详细说明以及案例
2025-03-11
59
参考资料
动态伪类选择器详细说明以及案例
动态伪类选择器用于匹配用户在特定状态下与元素交互的样式。常见的动态伪类选择器包括:
:hover
当用户将鼠标悬停在元素上时应用样式。a:hover { color: red; }:active
当用户激活(点击)元素时应用样式。button:active { background-color: blue; }:focus
当元素获得焦点(如输入框被选中)时应用样式。input:focus { border-color: green; }:visited
用于设置已访问链接的样式。a:visited { color: purple; }:link
用于设置未访问链接的样式。a:link { color: blue; }:target
当元素是当前URL的目标时应用样式(通常用于锚点链接)。#section1:target { background-color: yellow; }:checked
用于选中的复选框或单选按钮。input:checked { background-color: orange; }:disabled
用于禁用的表单元素。input:disabled { background-color: gray; }:enabled
用于启用的表单元素。input:enabled { background-color: white; }:valid 和 :invalid
:valid 用于有效输入的表单元素,:invalid 用于无效输入的表单元素。input:valid { border-color: green; } input:invalid { border-color: red; }
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态伪类选择器案例</title>
<style>
a:hover { color: red; }
button:active { background-color: blue; }
input:focus { border-color: green; }
a:visited { color: purple; }
a:link { color: blue; }
#section1:target { background-color: yellow; }
input:checked { background-color: orange; }
input:disabled { background-color: gray; }
input:enabled { background-color: white; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
</style>
</head>
<body>
<a href="#section1">跳转到Section 1</a>
<div id="section1">Section 1 Content</div>
<button>Click Me</button>
<input type="text" placeholder="Enter text">
<input type="checkbox"> Check me
<input type="text" required placeholder="Required field">
<input type="text" disabled placeholder="Disabled field">
</body>
</html>此案例展示了多种动态伪类选择器的应用效果。

