CSS - :active偽類屬性



CSS 中的:active偽類在使用者啟用元素時生效。因此,它表示啟用狀態下的元素,例如按鈕。

:active偽類主要用於

  • 諸如<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>
廣告