0

我正在尝试制作一个可以在三种颜色之间切换的按钮:黑色、绿色和红色,并且会根据颜色选中​​某个框。现在我可以进行颜色切换,但不能检查复选框。我将不胜感激。我是初学者(显然)。

按钮颜色绿色:复选框 1

按钮颜色红色:复选框 2

按钮颜色黑色:不选中框 1 或框 2

脚本如下所示:

<script>
var colors = ["green", "red", "black"] 

function setColor(el) { 
el.colorIdx = el.colorIdx || 0; 
el.style.color = colors[el.colorIdx++ % colors.length]; 
}

</script>

HTML 看起来像:

<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />  
</html>

谢谢!

4

2 回答 2

1

我建议:

var colors = ["green", "red", "black"];

function setColor(el) {
    el.colorIdx = el.colorIdx || 0;
    el.style.color = colors[el.colorIdx++ % colors.length];
    document.getElementById('box1').checked = el.style.color == 'green';
    document.getElementById('box2').checked = el.style.color == 'red';
}

JS 小提琴演示

于 2013-03-29T23:03:19.003 回答
0

像这样做:

var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
  document.getElementById("box1").checked = false; 
  document.getElementById("box2").checked = false; 
}
else if( index == 0 )
{
   document.getElementById("box1").checked = true;     
}
else
{
   document.getElementById("box2").checked = true;       
}
于 2013-03-29T23:01:15.173 回答