我对 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>
最佳答案
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>
关于javascript - 如何一键多次更改背景颜色(请仅使用 JavaScript)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285552/