每次按下交通信号灯时,如何制作一个不断改变灯光的按钮?

时间:2016-05-23 13:51:39

标签: javascript svg

我需要我的代码来不断更换灯光。每当我按下按钮,我希望红绿灯显示红色,然后红色和黄色一起显示绿色,我希望每次按下按钮时重复此过程。我需要帮助。到目前为止,我已经有了这段代码。

<!DOCTYPE html>
<html>
<head>
<title>Traffic Light</title>
</head>
<body>

<h1>Traffic Light</h1>
<p>Click the button for light to change.</p>

<div

style="width:100.5px;height:320px;border:3px solid #000;">

<button onclick=circle2.style.fill="yellow";><Change Lights
<button onclick=circle1.style.fill="transparent";><Change Lights
<button onclick=circle2.style.fill="transparent";><Change Lights
<button onclick=circle3.style.fill="green";>Change Lights
</button>

<svg id="svg1" style="width: 3.5in; height: 1in">
<circle id="circle1" r="40" cx="50" cy="50" style="fill: red; stroke: black;      stroke-width: 2"/>
</svg>

<svg id="svg2" style="width: 3.5in; height: 1in">
<circle id="circle2" r="40" cx="50" cy="50" style="fill: transparent; stroke: black; stroke-width: 2"/>
</svg>

<svg id="svg3"style="width: 3.5in; height: 1in">
<circle id="circle3" r="40" cx="50" cy="50" style="fill: transparent; stroke: black; stroke-width: 2"/>
</svg>

</script>
</div> 
</body>
</html>
你能帮我找到解决方案吗? 谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个

<p>Click the button for light to change.</p>

<div

style="width:100.5px;height:420px;border:3px solid #000;">

<button onclick='circle2.style.fill="yellow"'>Change Lights</button>
<button onclick='circle1.style.fill="transparent"'>Change Lights</button>
<button onclick='circle2.style.fill="transparent"'>Change Lights</button>
<button onclick='circle3.style.fill="green"'>Change Lights</button>

<svg id="svg1" style="width: 3.5in; height: 1in">
<circle id="circle1" r="40" cx="50" cy="50" style="fill: red; stroke: black;      stroke-width: 2"/>
</svg>

<svg id="svg2" style="width: 3.5in; height: 1in">
<circle id="circle2" r="40" cx="50" cy="50" style="fill: transparent; stroke: black; stroke-width: 2"/>
</svg>

<svg id="svg3"style="width: 3.5in; height: 1in">
<circle id="circle3" r="40" cx="50" cy="50" style="fill: transparent; stroke: black; stroke-width: 2"/>
</svg>

</div> 

答案 1 :(得分:0)

试试这个:

var circle = document.getElementById('circle');
var colors = ['red', 'yellow', 'green'];
var index = 0;
document.getElementById('traffic').onclick = function() {
  index++;
  if (index == colors.length) {
    index = 0;
  }
  circle.style.fill = colors[index];
};
<button id="traffic">Change Lights</button>

<svg id="svg" style="width: 3.5in; height: 1in">
<circle id="circle" r="40" cx="50" cy="50" style="fill: red; stroke: black;      stroke-width: 2"/>
</svg>