CSS3 的偽類選擇器種類繁多,其中有一類特別實用——狀態偽類選擇器。它們的共同特徵是:定義的樣式只在元素處於某種特定狀態時才生效,默認狀態下完全不起作用。
先來認識最常用的一組:
:hover——鼠標懸停在該元素上時套用的樣式。
:active——元素處於激活狀態(在元素上按下鼠標但尚未鬆開)時套用的樣式。
:focus——元素獲得焦點時套用的樣式,最常見的場景是輸入框中打字。
【注意】下面這個示例中,點擊後幾乎立刻變成綠色,並不是 active 沒生效,而是 active 觸發的同時 focus 也被觸發了,而 focus 的樣式覆蓋了它。想單獨觀察 active 的效果,把 focus 那行註釋掉再運行即可。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312">
<title>hover、active、focus 偽類選擇器示例</title>
<style type="text/css">
*{margin:0; padding:0;}
body{margin-bottom:20px; font-family:"Microsoft yahei"; font-size:14px;}
ul{margin:50px auto; width:260px; height:100px; list-style:none;}
ul li{margin-bottom:10px; overflow:hidden;}
label,input{display:inline; float:left;}
label{padding-right:8px; width:50px; height:27px; line-height:27px; text-align:right;}
input{width:200px; height:25px; border:1px #eee solid; border-top:1px #d1d1d1 solid; outline:none;}
input:hover{background:#eff7ff;}
input:active{background:#ffd;}
input:focus{background:#f2fddb;}
</style>
</head>
<body>
<ul>
<li>
<label for="userName">姓名:</label>
<input id="userName" type="text"/>
</li>
<li>
<label for="userPwd">密碼:</label>
<input id="userPwd" type="password"/>
</li>
</ul>
</body>
</html>
運行後可以觀察到三種顏色的變化:鼠標移入時是淺藍(hover),按下未鬆開瞬間是淡黃(active),點擊完成後因為 retains 焦點而停在淺綠(focus)。把三行樣式逐個註釋對比,最能看清它們的觸發時機。