无法读取未定义的属性“0”

时间:2013-12-11 18:51:28

标签: javascript

我需要使用我的网站文字来更改用户的滚动条。我使用一个简单的脚本。使用onscroll =“scroll()”在body标签内部调用它时工作正常。

这是我的javascript代码:

  var colors = [
  [212, 88, 27],
  [205, 91, 35],
  [200, 63, 46],
  [194, 60, 57],
  [174, 44, 64],
  [135, 44, 76],
  [109, 49, 85],
  [107, 50, 91],
  [85, 67, 96]
],

el = document.querySelectorAll('body, h1, h2, h3, h4, h5, h6')[0], // Element to be    scrolled
length = colors.length,                        // Number of colors
height = Math.round(el.offsetHeight / 9); // Height of the segment between two colors.  9 is the total amount of colors used

 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.color = ['hsl(', h, ', ', s+'%, ', l, '%)'].join('');
}

当我向上滚动并点击页面顶部时,加起来!未捕获的TypeError:无法读取以下行中未定义的属性“0”:

h = c1[0] + Math.round((c2[0] - c1[0]) * d),

我试图删除[0]而没有任何改变。

感谢您的帮助!

0 个答案:

没有答案