滚动时更改背景颜色 [英] Change Background-color on scroll

查看:132
本文介绍了滚动时更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wanting to create an effect like the one on the following page http://readymag.com/ where the background color changes depending on the scroll position but have no idea how to go about it and I can't understand their code.

我看过一些从1种颜色变为另一种颜色的例子,但我不确定如何用多种颜色来做。
(我希望能够指定每种颜色)

I've seen a few examples that change from 1 color to another but I'm unsure how to do it with multiple colors. (I would like to be able to specify each color)

任何帮助将不胜感激。

迈克尔。

推荐答案

这是一个简单的方法:

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

这篇关于滚动时更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆