当用户激活元素时,CSS 中的 :active 伪类就会起作用。因此,它代表激活时的一个元素,例如按钮。
:active pseudo-class 主要用于:- <a> 和 <button> 等元素。
- 放置在激活元素内的元素。
- 表单的元素,通过关联的<label>激活。
您必须将 :active 规则放在所有其他与链接相关的规则之后,这些规则由 LVHA 顺序定义,即 :link-:visited-:hover-active。这一点很重要,因为 :active 指定的样式会被后续与链接相关的伪类覆盖,例如 :link、:hover 或 :visited。
语法
selector:active {
/* ... */
}
CSS :active 示例
以下是更改链接的前景色和背景色的示例:
<html>
<head>
<style>
div {
padding: 1rem;
}
a {
background-color: rgb(238, 135, 9);
font-size: 1rem;
padding: 5px;
}
a:active {
background-color: lightpink;
color: darkblue;
}
p:active {
background-color: lightgray;
}
</style>
</head>
<body>
<div>
<h3>:active example - link</h3>
<p>This paragraph contains me, a link, <a href="#">see the color change when I am clicked!!!</a></p>
</div>
</body>
</html>
以下是在激活时更改按钮的边框、前景和背景颜色的示例:
<html>
<head>
<style>
div {
padding: 1rem;
}
button {
background-color: greenyellow;
font-size: large;
}
button:active {
background-color: gold;
color: red;
border: 5px inset grey;
}
</style>
</head>
<body>
<h3>:active example - button</h3>
</div>
<button>Click on me!!!</button>
</div>
</body>
</html>
下面是一个示例,其中使用伪类 :active 激活表单元素:
<html>
<head>
<style>
form {
border: 2px solid black;
margin: 10px;
padding: 5px;
}
form:active {
color: red;
background-color: aquamarine;
}
form button {
background: black;
color: white;
}
</style>
</head>
<body>
<h3>:active example - form</h3>
<form>
<label for="my-button">Name: </label>
<input id="name"/>
<button id="my-button" type="button">Click Me!</button>
</form>
</body>
</html>