gpt4 book ai didi

javascript - 制作一个像单选按钮一样的背景,单击它时会在打开状态和关闭状态之间切换

转载 作者:行者123 更新时间:2023-12-02 16:10:12 25 4
gpt4 key购买 nike

我对这个完全迷失了。

HTML:

<p onclick="on(&quot;test&quot;, testSwitch)" id="test" style="background:red;">TEST THIS STUFF OUT</p>

Js:

var testSwitch = 0;
function on(element, machineSwitch){
if (machineSwitch==0){
document.getElementById(element).style.display="green";
document.getElementById(element).innerHTML="STATUS:ON";
machineSwitch=1;
}
else if(machineSwitch==1){
document.getElementById(element).style.display="red";
document.getElementById(element).innerHTML="STATUS: OFF";
machineSwitch=0;
}
}

我正在尝试使背景在单击时变为绿色,然后在再次单击时变为红色。背景应该循环这些。我还需要一个变量来控制它,因为我用它来控制其他地方是否发生循环。

最佳答案

使用element.style.background更改背景颜色。

HTML

<p onclick="on(this)" id="test" style="background:red;">TEST THIS STUFF OUT</p>

JS

var testSwitch = 0;
var machineSwitch = 0;
function on(element){
if (machineSwitch==0){
element.style.background="green";
element.innerHTML="STATUS:ON";
machineSwitch=1;
} else if(machineSwitch==1){
element.style.background="red";
element.innerHTML="STATUS: OFF";
machineSwitch=0;
}
}

如果要添加更多颜色,使用 data- 属性会更方便,并使用 case switch 以获得更大的灵 active 。

JS

function on(element){
switch (element.getAttribute('data-machineSwitch')) {
case '0':
element.style.background="green";
element.innerHTML="STATUS:ON";
element.setAttribute('data-machineSwitch', '1');
break;
case '1':
element.style.background="red";
element.innerHTML="STATUS:OFF";
element.setAttribute('data-machineSwitch', '0');
break;
}
}

关于javascript - 制作一个像单选按钮一样的背景,单击它时会在打开状态和关闭状态之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com