我一直試圖想出一種方法來保持多個按鈕打開或以某種方式切換它們,我對 JavaScript 并沒有真正的經驗,但我看到你可以在點擊時添加一個類,但因為我已經有了,所以它不起作用一個班級。也許向元素添加 ID 可能有效?
我需要這個片段出現在每個在特定位置切換的按鈕上 <section>
button:focus {
background-color: #2ce98e;
color: #131621;
cursor: pointer;
}
提前致謝 :)
uj5u.com熱心網友回復:
希望這就是你要找的
單擊按鈕時切換類的存在
<!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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365655.html
標籤:javascript html css 按钮
