我发现这个简洁的脚本可以随机改变背景渐变颜色。
我想问,如何缩小颜色范围 - 我希望它只使用黄色和橙色的色调。
预先感谢:)
<p></p>
<pre><code>function newGradient() {
var c1 = {
r: Math.floor(Math.random()*255),
g: Math.floor(Math.random()*255),
b: Math.floor(Math.random()*255)
};
var c2 = {
r: Math.floor(Math.random()*255),
g: Math.floor(Math.random()*255),
b: Math.floor(Math.random()*255)
};
c1.rgb = 'rgb('+c1.r+','+c1.g+','+c1.b+')';
c2.rgb = 'rgb('+c2.r+','+c2.g+','+c2.b+')';
return 'radial-gradient(at top left, '+c1.rgb+', '+c2.rgb+')';
}
function rollBg() {
$('.bg.hidden').css('background', newGradient());
$('.bg').toggleClass('hidden');
}
</code></pre>
<p></p>
最佳答案
看这里:
var c1 = {
r: Math.floor(Math.random()*255),
g: Math.floor(Math.random()*255),
b: Math.floor(Math.random()*255)
};
var c2 = {
r: Math.floor(Math.random()*255),
g: Math.floor(Math.random()*255),
b: Math.floor(Math.random()*255)
};
随机两个RGB颜色从 0 到 255(最大)。您所要做的就是将颜色分量的随机值更改为黄色范围附近。黄色为r=255,g=255,b=0。因此您希望输出颜色接近这些值。
您可以使用 online rgb color pickers 之一搜索所需的颜色范围.
例如:
function newGradient() {
var c1 = {
r: Math.floor(255),
g: Math.floor(35+Math.random()*220),
b: Math.floor(Math.random()*55)
};
var c2 = {
r: Math.floor(255),
g: Math.floor(35+Math.random()*220),
b: Math.floor(Math.random()*85)
};
c1.rgb = 'rgb('+c1.r+','+c1.g+','+c1.b+')';
c2.rgb = 'rgb('+c2.r+','+c2.g+','+c2.b+')';
return 'radial-gradient(at top left, '+c1.rgb+', '+c2.rgb+')';
}
function rollBg() {
$('body').css('background', newGradient());
setTimeout(function(){rollBg();}, 1000);
}
rollBg();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
尝试不同的范围,直到得到你喜欢的东西。请确保不要超出 0-255 范围,并记住对于黄色,您需要高度 r 和 g 以及低 b。
关于javascript - 脚本随机改变背景渐变颜色[但从特定范围],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711766/