วิธีการ - เพิ่มคลาสที่ใช้งานให้กับองค์ประกอบปัจจุบัน
เรียนรู้วิธีเพิ่มคลาสที่ใช้งานให้กับองค์ประกอบปัจจุบันด้วย JavaScript
ไฮไลท์ปุ่มใช้งาน/ปัจจุบัน (กด):
องค์ประกอบที่ใช้งานอยู่
ขั้นตอนที่ 1) เพิ่ม HTML:
ตัวอย่าง
<div id="myDIV">
<button class="btn">1</button>
<button
class="btn active">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
</div>
ขั้นตอนที่ 2) เพิ่ม CSS:
ตัวอย่าง
/* Style the buttons */
.btn {
border: none;
outline:
none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
/* Style the active class (and buttons on
mouse-over) */
.active, .btn:hover {
background-color: #666;
color: white;
}
ขั้นตอนที่ 3) เพิ่ม JavaScript:
ตัวอย่าง
// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns =
btnContainer.getElementsByClassName("btn");
// Loop through
the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length;
i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
หากคุณไม่ได้ตั้งค่าคลาสแอ็คทีฟบนองค์ประกอบปุ่มเพื่อเริ่มต้น ให้ใช้รหัสต่อไปนี้:
ตัวอย่าง
// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns =
btnContainer.getElementsByClassName("btn");
// Loop through
the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length;
i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
// If there's no active class
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
// Add the active class to the current/clicked
button
this.className += " active";
});
}