Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

Pseudo-class :active ใน CSS สำหรับสถานะกด/คลิก

Pseudo-class :active ใช้จับสถานะที่ element กำลังถูก "กระทำ" (activated) โดยผู้ใช้ เช่น กำลังถูกคลิก (mousedown) กำลังถูกกดปุ่มบนแป้นพิมพ์ หรือ กำลังถูกแตะ (touch)

รูปแบบไวยากรณ์

a:active { color: green; }

ตัวอย่างที่ 1: เปลี่ยนสีลิงก์ขณะคลิก

<html>
<head>
  <style>
    a:active { color: green; }
  </style>
</head>
<body>
  <a href="https://www.tutorialspoint.com">Click here to learn</a>
</body>
</html>

คำอธิบาย: ขณะกำลังคลิกค้างที่ลิงก์ สีจะกลายเป็นเขียว (ปล่อยเมาส์จะกลับสู่ปกติหรือ :visited)

ตัวอย่างที่ 2: เปลี่ยนขนาดฟอนต์ขณะคลิก

<html>
<head>
  <style>
    a:active { font-size: 20px; }
  </style>
</head>
<body>
  <a href="https://www.tutorialspoint.com">Click here to learn</a>
</body>
</html>

คำอธิบาย: ขนาดฟอนต์จะใหญ่ขึ้นเป็น 20px เฉพาะขณะคลิกค้าง

ตัวอย่างที่ 3: ใช้กับ body - คลิกที่ไหนก็ได้ในหน้า

<html>
<head>
  <style>
    body:active { background: seagreen; }
  </style>
</head>
<body>
  <div>click anywhere in this window</div>
</body>
</html>

คำอธิบาย: คลิกที่ไหนในหน้าก็ตาม พื้นหลังจะกลายเป็นสี sea green ขณะกดค้าง

ตัวอย่างที่ 4: ใช้กับปุ่ม (button)

<html>
<head>
  <style>
    #thisButton:active { color: red; }
  </style>
</head>
<body>
  <button id="thisButton">Click Me!!</button>
</body>
</html>

คำอธิบาย: ตัวอักษรปุ่มจะกลายเป็นสีแดงขณะกดค้าง

Browser Compatibility

ChromeFirefoxEdgeIESafariOpera
11Yes415

ข้อสังเกต: :active ทำงานได้กับทุก element ไม่ใช่แค่ลิงก์ (ต่างจาก :visited) เหมาะสำหรับ feedback การโต้ตอบ (pressed state) ของปุ่ม, การ์ด, リストไอเท็ม