我有一个背景,每次点击一个按钮时都会随机改变颜色。是否有可能确保每次点击时颜色不同(避免连续2-3次产生相同颜色的可能性)?下面是.js文件的源代码(HTML基本上就是按钮)。
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 :(得分: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);
&#13;
#target{
width: 100px;
height: 100px;
margin: 1em;
background-color: rgb(255, 255, 255);
}
&#13;
<div id="target"></div>
&#13;