[英]With single button, how to change div background color in order listed, not randomly
我正在使用下面的代码来更改按钮单击时 div 的背景颜色。 它随机选择颜色(math.random),但我希望它按列出的顺序选择颜色(红色>蓝色>黄色>等)。 谁能帮我这个? 提前致谢!
<style>
#changecolor2 {
height: 100px;
width: 100px;
}
</style>
<script>
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {
var col = document.getElementById("changecolor");
col.style.backgroundColor = colors[Math.floor((Math.random()*8)+1)];
}
</script>
<body>
<div id="changecolor2"></div>
<button onclick="changeColor();">change color</button>
</body>
只需维护一个跟踪当前颜色索引的变量即可。 如果它到达最后一种颜色,只需返回到第一种颜色。
var current = -1;
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {
if(current > colors.length-1){
current = 0;
} else {
current++;
}
var col = document.getElementById("changecolor");
col.style.backgroundColor = colors[current];
}
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("changecolor2");
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
}
window.onload = changeColor;
<script type="text/javascript">
var count = 0;
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {
if(count >= colors.length-1){
count = 0;
} else {
count++;
}
document.getElementById("changecolor2").style.backgroundColor = colors[count];
}
</script>
这将对您有所帮助,并将以循环方式更改背景颜色。
var colors = ["red", "green", "blue"];
var count = 0;
$(".button").click(function() {
$("body").css("background-color", colors[count]);
count++
count >= colors.length ? count = 0: count ;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.