2016-08-16 102 views
0

我有一個背景,每次單擊按鈕時隨機更改顏色。是否可以確保每次點擊後顏色都不同(避免連續產生2-3次相同顏色的可能性)? .js文件的源代碼如下(HTML基本上就是按鈕)。隨機bgColor:每次點擊的顏色有可能不同嗎?

var bgcolorlist, btn; 
function newColor() { 
    bgcolorlist = '#'+Math.floor(Math.random()*16777215).toString(16); 
    document.body.style.backgroundColor = bgcolorlist; 
} 
function initAll() { 
    btn = document.getElementById('click1'); 
    btn.addEventListener('click', newColor, false); 
} 
initAll(); 
+0

添加顏色到數組中,如果它在數組中,則生成一個新數組。 – epascarello

+0

我可能會問,'document.body.style.backgroundColor'的用途是在'initAll()'中嗎? – Xenyal

+1

什麼是您的「相同顏色」的定義/閾值。鑑於簡單地採取任意隨機顏色有一千六百萬重複的機會我覺得你可能在確保顏色明顯不同之後。 – JonSG

回答

1

嘗試以下方法:

var bgcolorlist, btn; 
var colorList = []; 
function newColor() { 
    bgcolorlist = '#'+Math.floor(Math.random()*16777215).toString(16); 
    while(colorList.indexOf(bgcolorlist) != -1){ 
    bgcolorlist = '#'+Math.floor(Math.random()*16777215).toString(16); 
    } 
    colorList.push(bgcolorlist); 
    document.body.style.backgroundColor = bgcolorlist; 
} 
function initAll() { 
    btn = document.getElementById('click1'); 
    btn.addEventListener('click', newColor, false); 
} 
initAll(); 
+0

欣賞給出的解決方案。我可以知道在函數initAll中添加'document.body.style.backgroundColor;'的目的嗎? –

+0

@GopinathShiva錯字哎呀:) –

+0

@Gopinath溼婆 - 謝謝,額外的行現在被刪除。 – ABCode

0

這裏是一個版本具有恆定時間查找到該組先前產生的顏色。如果顏色數組變大,那麼使用這種方法將顯着提高速度,優於使用的顏色數組。

var usedColors = {}; 
function randomColor() { 
    return Math.floor(Math.random() * 0xFFFFFF).toString(16); 
} 
function unusedColor() { 
    var color; 
    while ((color = randomColor()) in usedColors); 
    usedColors[color] = true; 
    return '#' + color; 
} 
window.onload = function() { 
    document.body.style.backgroundColor = unusedColor(); 
}; 
0

此策略每個信道相比較(新舊),並確保由信道基礎的信道上存在至少最小的變化(閾值)

function getChannelColor(color, threshold){ 
 
    var _new = 0; 
 
    var _tooCloseMin = color - threshold; 
 
    var _tooCloseMax = color + threshold; 
 

 
    do { _new = Math.floor(Math.random() * 256); } 
 
    while (_tooCloseMin < _new && _new < _tooCloseMax); 
 

 
    return _new; 
 
} 
 

 
setInterval(function(){ 
 
    var target = document.getElementById("target"); 
 
    var threshold = 5; 
 

 
    var prevRGB = getComputedStyle(target).backgroundColor.match(/\d+/g); 
 
    var prevR = parseInt(prevRGB[0]); 
 
    var prevG = parseInt(prevRGB[1]); 
 
    var prevB = parseInt(prevRGB[2]); 
 

 
    var newR = getChannelColor(prevR, threshold); 
 
    var newG = getChannelColor(prevG, threshold); 
 
    var newB = getChannelColor(prevB, threshold); 
 
    
 
    target.style.backgroundColor = "rgb(" + newR + ", " + newG + ", " + newB + ")"; 
 
}, 1000);
#target{ 
 
    width: 100px; 
 
    height: 100px; 
 
    margin: 1em; 
 
    background-color: rgb(255, 255, 255); 
 
}
<div id="target"></div>