gpt4 book ai didi

javascript - 更改滚动条上的背景颜色

转载 作者:行者123 更新时间:2023-12-02 18:40:58 25 4
gpt4 key购买 nike

我想要创建一个如下页 http://readymag.com/ 所示的效果背景颜色根据滚动位置而变化,但不知道如何去做,我无法理解他们的代码。

我见过一些从一种颜色更改为另一种颜色的示例,但我不确定如何使用多种颜色进行更改。(我希望能够指定每种颜色)

任何帮助将不胜感激。

迈克尔。

最佳答案

这里有一个简单的方法:

HTML

<body onscroll="scroll()">
...
</body>

JavaScript

// HSL Colors
var colors = [
[0, 100, 50],
[113, 75, 25],
[240, 87, 40],
[328, 24, 40]
],

el = document.getElementsByTagName('body')[0], // Element to be scrolled
length = colors.length, // Number of colors
height = Math.round(el.offsetHeight / length); // Height of the segment between two colors

function scroll() {
var i = Math.floor(el.scrollTop / height), // Start color index
d = el.scrollTop % height / height, // Which part of the segment between start color and end color is passed
c1 = colors[i], // Start color
c2 = colors[(i+1)%length], // End color
h = c1[0] + Math.round((c2[0] - c1[0]) * d),
s = c1[1] + Math.round((c2[1] - c1[1]) * d),
l = c1[2] + Math.round((c2[2] - c1[2]) * d);
el.style['background-color'] = ['hsl(', h, ', ', s+'%, ', l, '%)'].join('');
}

工作示例:http://jsbin.com/elolud/2/edit

关于javascript - 更改滚动条上的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16844723/

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