簡體   English   中英

使用單個按鈕,如何按列出的順序更改 div 背景顏色,而不是隨機更改

[英]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;

小提琴: http : //jsfiddle.net/aslancods/6S46U/

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM