如何让多个按钮处于焦点状态? HTML/CSS/JS
How to have multiple buttons in focus? HTML/CSS/JS
我一直在尝试想出一种方法来保持多个按钮打开或以某种方式切换它们,我对 JavaScript 没有真正的经验,但我看到你可以添加一个 class 单击但不会工作,因为我已经设置了 class。也许向元素添加 ID 可能有效?
我需要将此代码段放在特定 <section>
中打开的每个按钮上
button:focus {
background-color: #2ce98e;
color: #131621;
cursor: pointer;
}
提前致谢:)
希望这就是您要找的
点击按钮时切换 class 的存在状态
<!DOCTYPE html>
<html lang="en">
<head>
<title>Toggle buttons</title>
<style>
.button-focus {
background-color: #2ce98e;
color: #131621;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn btn-one">Button one</button>
<button class="btn btn-two">Button two</button>
</body>
<script>
// get all the elements on the basis of their class name
let btn = document.getElementsByClassName("btn");
for (var i = 0; i < btn.length; i++) {
(function (index) {
btn[index].addEventListener("click", function () {
console.log("Clicked Button: " + index);
let isPresent = false;
// Check if the class is present or not
this.classList.forEach(function (e, i) {
if (e == "button-focus") {
isPresent = true;
} else {
isPresent = false;
}
});
// toggle the presence of class on the basis of the isPresent variable
if (isPresent) {
this.classList.remove("button-focus");
} else {
this.classList.add("button-focus");
}
});
})(i);
}
</script>
</html>
我一直在尝试想出一种方法来保持多个按钮打开或以某种方式切换它们,我对 JavaScript 没有真正的经验,但我看到你可以添加一个 class 单击但不会工作,因为我已经设置了 class。也许向元素添加 ID 可能有效?
我需要将此代码段放在特定 <section>
button:focus {
background-color: #2ce98e;
color: #131621;
cursor: pointer;
}
提前致谢:)
希望这就是您要找的
点击按钮时切换 class 的存在状态
<!DOCTYPE html>
<html lang="en">
<head>
<title>Toggle buttons</title>
<style>
.button-focus {
background-color: #2ce98e;
color: #131621;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn btn-one">Button one</button>
<button class="btn btn-two">Button two</button>
</body>
<script>
// get all the elements on the basis of their class name
let btn = document.getElementsByClassName("btn");
for (var i = 0; i < btn.length; i++) {
(function (index) {
btn[index].addEventListener("click", function () {
console.log("Clicked Button: " + index);
let isPresent = false;
// Check if the class is present or not
this.classList.forEach(function (e, i) {
if (e == "button-focus") {
isPresent = true;
} else {
isPresent = false;
}
});
// toggle the presence of class on the basis of the isPresent variable
if (isPresent) {
this.classList.remove("button-focus");
} else {
this.classList.add("button-focus");
}
});
})(i);
}
</script>
</html>