หลักการทำงาน
ใช้คุณสมบัติ opacity ลดความทึบของปุ่ม เพื่อสร้างลักษณะ "Disabled" หรือ "ไม่สามารถกดได้" โดยไม่ต้องใช้ attribute disabled จริงๆ
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<head>
<style>
.btn {
color: black;
text-align: center;
font-size: 16px;
padding: 12px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: opacity 0.3s ease;
}
.btn-enabled {
background-color: #007bff;
color: white;
}
.btn-disabled-look {
background-color: #007bff;
color: white;
opacity: 0.5; /* ลดความทึบเหลือ 50% */
cursor: not-allowed; /* เปลี่ยนเคอร์เซอร์ */
pointer-events: none; /* ป้องกันการคลิก (optional) */
}
</style>
</head>
<body>
<h2>เปรียบเทียบปุ่ม Enabled และ Disabled Look</h2>
<button class="btn btn-enabled">Enabled (พร้อมใช้งาน)</button>
<button class="btn btn-disabled-look">Disabled Look (ลักษณะปิด)</button>
</body>
</html>
ความแตกต่าง: Disabled Look vs Disabled จริง
| คุณสมบัติ | Disabled Look (opacity) | Disabled จริง (attribute) |
|---|---|---|
| สามารถกดได้ | ได้ (ต้องใช้ pointer-events: none) | ไม่ได้ |
| ส่งฟอร์ม | ส่งได้ | ไม่ส่ง |
| เข้าถึงด้วย Tab | ได้ | ไม่ได้ |
| Accessibility | ต้องเพิ่ม aria-disabled="true" | รองรับอัตโนมัติ |
แนวทางปฏิบัติที่ดีที่สุด (Best Practice)
/* ปุ่ม disabled จริง - แนะนำให้ใช้วิธีนี้ */
button:disabled,
button[aria-disabled="true"] {
opacity: 0.6;
cursor: not-allowed;
background-color: #ccc;
color: #666;
}
/* สำหรับ custom button ที่ไม่ใช่ <button> */
.custom-btn[aria-disabled="true"] {
opacity: 0.5;
pointer-events: none;
cursor: not-allowed;
}
คำแนะนำ
- ควรใช้
disabledattribute จริงๆ สำหรับ<button>และ<input> - ใช้ opacity ระหว่าง 0.5 - 0.7 สำหรับลักษณะ disabled
- เพิ่ม
cursor: not-allowedเพื่อบ่งชี้สถานะให้ผู้ใช้ - สำหรับ Accessibility ต้องเพิ่ม
aria-disabled="true"