动态伪类选择器详细说明以及案例
2025-03-11
31
参考资料
动态伪类选择器用于匹配用户在特定状态下与元素交互的样式。常见的动态伪类选择器包括:
: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>此案例展示了多种动态伪类选择器的应用效果。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-199.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
