对于HTML按钮:
<button type="button" id="100">100%</button>
我有一个Java脚本功能,可以交换该按钮的2种背景颜色:
const but1 = document.getElementById("100");
n=0;
but.addEventListener("click", function (){
if (n==0) {
but1.style.backgroundColor = "rgb(225, 165, 0)";
n=1;
} else {
but1.style.backgroundColor = "rgb(225, 165, 0,0)";
n=0;
}
});
效果很好。但是我想创建更多按钮,并且不想每次都复制相同的功能。为了简化起见,我编写了一个将带有参数的函数,假设“ b”(对于按钮),“ c1”和“ c2”(对于颜色),和“ x”-表示“ n”值(对于每个按钮)。所以我的Java脚本(用于HTML按钮)带有两个按钮的示例集
const but1 = document.getElementById("button");
n=0;
function colorSwitch (b, c1, c2, x){
if (x==0) {
b.style.backgroundColor = c1;
x=1;
} else {
b.style.backgroundColor = c2;
x=0;
}
}
// orange set
const cOrange = "rgb(225, 165, 0)";
const cOrangeT = "rgb(225, 165, 0,0)";
but1.addEventListener("click", function(){
colorSwitch(but1, cOrange, cOrangeT, n);
});
我遇到的问题是使用“ x”参数。似乎抢占了初始的“ 0”值,然后将其设置为“ 1”。但是当我再次单击按钮时,初始值再次为“ 0”。因此没有循环,颜色也不会交换。
我对“ x”的行为不了解什么,以及如何正确编码?
classList.toggle()
切换样式Element.classList.toggle()
,以toggle一个.is-active
CSS类:
const btns = document.querySelectorAll(".btnTog");
btns.forEach(btn => {
btn.addEventListener('click', () => {
btn.classList.toggle('is-active');
});
})
.btnTog {
border: 0;
padding: 0.5em;
background-color: rgba(225, 165, 0, 0.5);
}
.is-active {
background-color: rgba(255, 180, 0, 1)
}
<button class="btnTog" type="button">100%</button>
<button class="btnTog" type="button">100%</button>
使用data-*
属性切换颜色以存储状态(1/0)[如果出于某些未知原因要在元素内部存储状态,则可以使用超级方便的
data-*
属性:const btns = document.querySelectorAll(".btnTog"); const btnColors = [ "rgba(225, 165, 0, 0.5)", "rgba(255, 180, 0, 1)", ]; btns.forEach(btn => { btn.addEventListener('click', () => { btn.dataset.tog ^= 1; // Toggle 1, 0, 1, 0... btn.style.backgroundColor = btnColors[btn.dataset.tog]; }); })
.btnTog { border: 0; padding: 0.5em; background-color: rgba(225, 165, 0, 0.5); }
<button class="btnTog" type="button">100%</button> <button class="btnTog" type="button">100%</button>
function colorSwitch (b, c1, c2){
if (b.style.backgroundColor === c1) {
b.style.backgroundColor = c2;
} else {
b.style.backgroundColor = c1;
}
}