有没有办法自动改变背景颜色的阴影?

时间:2021-02-16 13:57:18

标签: javascript html css

想知道是否有一种方法可以使用光谱根据诸如温度之类的变量来更改背景颜色,温度越高,颜色从蓝色变为橙色越多?或者我真的必须赋值

if (temp < 10) {
document.body.className = "background-cold";
} else if (temp > 10) {
document.body.className = "background-warm";
}
.background-cold {
  background: linear-gradient(
    179.31deg,
    rgba(48, 87, 89, 0.97) 9.28%,
    #fdfeff 167.45%
  );
}

.background-warm {
  background: linear-gradient(
    179.31deg,
    rgba(204, 101, 26, 0.97) 9.28%,
    #fdfeff 167.45%
  );
}

2 个答案:

答案 0 :(得分:0)

var hue = temp * someScale; // use some formula to determine the appropriate hue from the temperature
var saturation = 1;
var lightness = 1;
document.body.style.backgroundImage = `linear-gradient(179.31deg, hsla(${hue}%,${saturation}%,${lightness}%) 9.28%, #fdfeff 167.45%)`;

答案 1 :(得分:0)

对于您打算采用的方法,我不建议使用 .className 属性。它将被硬编码,这不是您想要的。您可以只使用 style.setProperty(string, string),其中第一个参数是 CSS 属性,第二个参数是 CSS 值。它们都需要是字符串才能工作。

let colorValue = 'linear-gradient(VALUES)';
document.body.style.setProperty('background', colorValue);

通过使用之前的代码,您现在可以直接设置您想要的背景。但是,您仍然需要一个函数来根据温度创建动态的colorValue。根据您打算应用的颜色值,这可能会变得有点复杂。可以在以下链接中找到可能的解决方案:https://stackoverflow.com/a/12934900/11860800

希望这个回答对你有帮助!快乐编码!