2017-04-07 25 views
0

我有点新来JavaScript,我基本上想弄清楚如何有一个按钮,点击后改变背景颜色。目前我可以用三个单独的按钮来完成,但我不知道如何用一个按钮来完成。如何用一个按钮多次更改背景颜色(仅限JavaScript)?

单击我想要选择列表中的下一个颜色。

我没有关于JQuery的知识,所以如果代码不在JQuery中,我将不胜感激。

这是我的时刻:

<button onclick="myFunction1()">Red</button> 
<script type="text/javascript">function myFunction1() { 
document.body.style.backgroundColor = "red"; 
}</script> 

<button onclick="myFunction2()">Blue</button> 
<script type="text/javascript">function myFunction2() { 
document.body.style.backgroundColor = "blue"; 
}</script> 

<button onclick="myFunction3()">Green</button> 
<script type="text/javascript">function myFunction3() { 
document.body.style.backgroundColor = "green"; 
}</script> 

回答

1

const changeColor = document.getElementById('changeColor'), 
 
     colors  = ['red', 'green', 'blue']; 
 
let colorIndex = 0; 
 

 
changeColor.addEventListener('click',() => { 
 
    document.body.style.backgroundColor = colors[colorIndex];  
 
    colorIndex = (colorIndex + 1) % colors.length 
 
});
<button id="changeColor">changeColor</button>

+0

感谢您的评论,而不是三个单独的按钮,我只想要一个按钮,每次单击它时将颜色更改为红色,蓝色或绿色。 – johnny

+0

@johnny:误解了ES6中的问题。 – Przemek

+1

没问题。感谢您的帮助! – johnny

1

var colors = ["red", "blue", "green", "yellow"], // the color choices 
 
    index = 0;          // index of the current color 
 
    
 
document.getElementById("colorify").onclick = function() { 
 
    document.body.style.background = colors[index]; // set the color of body to the current color 
 
    index = (index + 1) % colors.length;    // increment index to point to the next color (if it goes beyond the length of the coices array get it back to 0 using the modulo %) 
 
}
<button id="colorify">Change color</button>

+0

谢谢你的帮助! – johnny

0

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Title</title> 
 
</head> 
 
<body> 
 
    <button onclick="changeColor()">click me</button> 
 
    <script> 
 
     var place =0; 
 
     function changeColor() { 
 
      // your color list 
 
      var colorList = ["red","green","blue"]; 
 
      // set the color 
 
      document.body.style.backgroundColor = colorList[place]; 
 
      place++; 
 
      // if place is greater than the list size, reset 
 
      if (place ===colorList.length) place=0; 
 
     } 
 
    </script> 
 
</body> 
 
</html>

+0

谢谢你的帮助! – johnny

相关问题