gpt4 book ai didi

javascript - 滚动时通过 Javascript 更改 CSS 背景渐变

转载 作者:行者123 更新时间:2023-12-04 09:40:44 26 4
gpt4 key购买 nike

我正在尝试通过 Javascript 更改渐变的两种背景颜色之一。颜色取决于滚动。不知何故,单一颜色有效但不是渐变。

const [red, green, blue] = [0, 200, 0];
const hasGradient = document.querySelector('.has-gradient');

window.addEventListener('scroll', () => {
let y = 1 + (window.scrollY || window.pageYOffset) / 150;
y = y < 1 ? 1 : y
const [r, g, b] = [red/y, green/y, blue/y].map(Math.round);
hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0));`;
console.log(`linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`)
});

感谢任何输入!

最佳答案

您使用的是 ;在你的字符串中。

  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0));`;

应该:
  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`;

Note: It is not possible to set styles by assigning a string to the style property, e.g. element.style = "color: red;". To set the style of an element, append a "CSS" property to style and specify a value



引用: https://www.w3schools.com/jsref/prop_html_style.asp

演示: https://jsfiddle.net/faod18mL/

关于javascript - 滚动时通过 Javascript 更改 CSS 背景渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62345425/

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