Cách thực hiện - Thêm lớp hoạt động vào phần tử hiện tại
Tìm hiểu cách thêm lớp hoạt động vào phần tử hiện tại bằng JavaScript.
Đánh dấu nút hoạt động/hiện tại (đã nhấn):
Yếu tố hoạt động
Bước 1) Thêm HTML:
Ví dụ
<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>
Bước 2) Thêm CSS:
Ví dụ
/* 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;
}
Bước 3) Thêm JavaScript:
Ví dụ
// 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";
});
}
Hãy tự mình thử »Nếu bạn chưa đặt lớp hoạt động trên thành phần nút để bắt đầu, hãy sử dụng mã sau:
Ví dụ
// 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";
});
}
Hãy tự mình thử »