DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
CSS3 實戰:搞懂 :hover、:active 與 :focus 的差別
編輯:CSS詳解     

CSS 的偽類選擇器種類繁多,其中「狀態偽類」這一族有個共同特徵:所定義的樣式只有在元素處於某種狀態時才生效,預設狀態下完全不影響外觀。

今天先來釐清最常被搞混的三個:

  • :hover——滑鼠指標懸停在元素上方時套用。
  • :active——元素處於啟用狀態(滑鼠已按下但尚未放開)時套用。
  • :focus——元素取得焦點時套用,最常用在文字輸入框上。

容易誤判的一點:在輸入框上點擊時,之所以幾乎立刻看到 focus 的綠色,是因為 active 觸發的同時 focus 也一起觸發了,於是 active 的效果看起來「沒作用」。想驗證的話,把 focus 那行程式碼註解掉再跑一次就看得很清楚。

完整範例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<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>

兩個實務提醒

outline:none 要謹慎。範例中為了視覺乾淨把焦點外框關掉了,但這其實會傷害鍵盤使用者的體驗。正式專案建議保留 outline,或改用自訂的 focus 樣式(例如邊框換色+外陰影)來兼顧美感與可辨識性。

label 的 for 屬性別省。把 for 對上 input 的 id,點擊文字就能聚焦到對應欄位,這是無障礙設計的基本功,同時也很好用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved