使背景像单选按钮一样在打开状态和关闭状态之间切换,当单击它时
Making a background like a radio button switching between an on state on off state when clicking on it
我完全搞不懂了。
Html:<p onclick="on("test", 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
更改BG颜色
<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
属性更方便,更灵活。
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;
}
}
<p onclick="on('test', testSwitch)" id="test" style="background:red;">TEST THIS STUFF OUT</p>
<script>
var testSwitch = 0;
function on(element, machineSwitch){
if (machineSwitch==0){
document.getElementById(element).style.backgroundColor ="green";
document.getElementById(element).innerHTML="STATUS:ON";
testSwitch=1;
}
else if(machineSwitch==1){
document.getElementById(element).style.backgroundColor="red";
document.getElementById(element).innerHTML="STATUS: OFF";
testSwitch=0;
}
}
</script>
相关文章:
- angular ui路由器卡在两个状态之间
- UI 路由器 - 在状态之间转换时记住滚动位置
- 在状态之间传递对象
- 如何使用 Angular JS 在状态之间导航
- 离子 - 在状态之间移动时,页面内容位于屏幕外部
- 如何在状态之间传递变量
- 在 ui 路由器状态之间发送事件
- 角度 UI.路由器在两种状态之间的倾斜过渡
- 在javascript中的打开/关闭状态之间循环
- 在ui路由器中的状态之间共享ng模型数据
- 正在寻找一个可用于在3个状态之间循环的JavaScript开关控件
- 按钮在状态之间切换
- 如何在angularjs中使用两个不同的ui路由器在状态之间共享作用域数据?
- Angular UI路由器使用go函数在状态之间传递数据不起作用
- js:如何在动画循环中的3个动画序列状态之间顺利过渡
- 不能在angular ui.router中的子状态之间切换
- 查找值和设置状态之间的范围
- 我如何在JavaScript中以编程方式创建的状态之间切换
- 在Javascript行为不规律的情况下在两种状态之间应用转换
- 在3个状态之间切换