Pseudo-class ใช้สำหรับจับสถานะพิเศษของ element เช่น :hover, :active, :focus และ :visited สำหรับลิงก์ (<a>) ที่ผู้ใช้เคยคลิก/เยี่ยมชมแล้ว
รูปแบบไวยากรณ์
a:visited { color: green; }
ตัวอย่างที่ 1: เปลี่ยนสีลิงก์ที่เคยเยี่ยมชม
<html>
<head>
<style>
a:visited { color: green; }
</style>
</head>
<body>
<a href="https://www.tutorialspoint.com">Click here to learn</a>
</body>
</html>
คำอธิบาย: ลิงก์จะเป็นสีฟ้า (default) ตอนยังไม่เคยเยี่ยมชม เมื่อคลิกแล้วจะกลายเป็นสีเขียว
ตัวอย่างที่ 2: เพิ่ม border ให้ลิงก์ที่เคยเยี่ยมชม
<html>
<head>
<style>
a { background-color: white; border: 1px solid white; }
a:visited { border: 1px solid yellow; }
</style>
</head>
<body>
<a href="https://www.tutorialspoint.com">Click here to learn</a>
</body>
</html>
คำอธิบาย: ลิงก์ที่เคยเยี่ยมชมจะมี border สีเหลือง 1px
ตัวอย่างที่ 3: เปลี่ยนพื้นหลังลิงก์ที่เคยเยี่ยมชม
<html>
<head>
<style>
a { background-color: white; }
a:visited { background-color: seagreen; }
</style>
</head>
<body>
<a href="https://www.tutorialspoint.com">Click here to learn</a>
</body>
</html>
คำอธิบาย: พื้นหลังลิงก์จะกลายเป็นสี sea green หลังเยี่ยมชม
ข้อจำกัดด้านความปลอดภัย (Security/Privacy Restrictions)
เพื่อป้องกันการติดตามประวัติการเข้าเว็บ (history sniffing) บราวเซอร์จำกัดคุณสมบัติ CSS ที่ใช้กับ :visited ให้เหลือเพียง:
- สี:
color,background-color,border-color,border-bottom-color,border-left-color,border-right-color,border-top-color,column-rule-color,outline-color - SVG attributes:
fill,stroke
ไม่สามารถใช้ได้: font-size, display, visibility, opacity, transform, background-image, margin, padding เป็นต้น
นอกจากนี้ getComputedStyle() จะคืนค่าเหมือน unvisited link เสมอ เพื่อป้องกัน JavaScript sniffing
Browser Compatibility
| Chrome | Firefox | Edge | IE | Safari | Opera |
|---|---|---|---|---|---|
| 1 | 1 | Yes | Yes | 1 | 3.5 |