gpt4 book ai didi

javascript - 如何将颜色百分比更改为 RGB

转载 作者:行者123 更新时间:2023-11-28 02:48:13 25 4
gpt4 key购买 nike

我创建了从绿色到红色的颜色代码 0-70。现在,我想将颜色 0 - 70 从红色更改为绿色。

function percentToRGB(percent) {
if (percent === 100) {
percent = 99
}
var r, g, b;

if (percent < 50) {
// green to yellow
r = Math.floor(255 * (percent / 50));
g = 255;

} else {
// yellow to red
r = 255;
g = Math.floor(255 * ((50 - percent % 50) / 50));
}
b = 0;

return "rgb(" + r + "," + g + "," + b + ")";
}


function render(i) {
var item = "<li style='background-color:" + percentToRGB(i) + "'>" + i + "</li>";
$("ul").append(item);
}

function repeat(fn, times) {
for (var i = 0; i < times; i++) fn(i);
}


repeat(render, 100);
li {
font-size:8px;
height:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

最佳答案

您应该能够在 percentToRGB 函数内切换 gr 变量。这是一个 JSFiddle Link .

所以函数会变成:

function percentToRGB(percent) {
if (percent === 100) {
percent = 99
}
var r, g, b;

if (percent < 50) {
// green to yellow
g = Math.floor(255 * (percent / 50));
r = 255;

} else {
// yellow to red
g = 255;
r = Math.floor(255 * ((50 - percent % 50) / 50));
}
b = 0;

return "rgb(" + r + "," + g + "," + b + ")";
}

关于javascript - 如何将颜色百分比更改为 RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com