更改滚动的背景色

时间:2018-11-26 21:04:19

标签: jquery css colors

我将此JavaScript与colors.js结合使用,可在滚动时更改背景色。效果很好,我唯一要做的就是在下一个div显示后就已经完成淡入淡入处理。

我的代码笔的例子;当您开始滚动时,背景会从白色逐渐变为黑色,但是当第二部分显示在底部时,我希望它已经是全黑了。

Codepen: https://codepen.io/pixelarchitect/pen/PxBmXB

var sections = [];
var sectionsYStart = [];
var activeSection = 0;

var pageInit = function() {
  sections = [];
  sectionsYStart = [];
  $("section").each(function(i, v) {
    sections[i] = v;
    sectionsYStart[i] = $(v).offset().top;
  });
};

var ChangeColorOnScroll = function() {
  var scroll = $(window).scrollTop();
  scrollColors(scroll, $("body"), ["#FFFFFF", "#000000"]);
}

var scrollColors = function(scroll, el, colors) {
  // which of all the sections, are we in between?
  var z = 0,
    seclen = sections.length;
  for (var i = 0; i < seclen; i++) {
    if (scroll > sectionsYStart[i]) {
      z = i;
    }
  }
  activeSection = z;

  scroll_pos = scroll;
  var animation_begin_pos = sectionsYStart[z]; //where you want the animation to begin
  var animation_end_pos = sectionsYStart[z + 1]; //where you want the animation to stop
  var beginning_color = $.Color(colors[z]);
  var ending_color = $.Color(colors[z + 1]);

  if (scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos) {
    var percentScrolled = scroll_pos / (animation_end_pos - animation_begin_pos);
    if (percentScrolled > 1) {
      percentScrolled = percentScrolled - z;
    }
    var newRed = beginning_color.red() + ((ending_color.red() - beginning_color.red()) * percentScrolled);
    var newGreen = beginning_color.green() + ((ending_color.green() - beginning_color.green()) * percentScrolled);
    var newBlue = beginning_color.blue() + ((ending_color.blue() - beginning_color.blue()) * percentScrolled);

    var newAlpha = beginning_color.alpha() + ((ending_color.alpha() - beginning_color.alpha()) * percentScrolled);

var newColor = new $.Color(newRed, newGreen, newBlue, newAlpha);
el.animate({
  backgroundColor: newColor
}, 0);
  } else if (scroll_pos > animation_end_pos) {
    el.animate({
      backgroundColor: ending_color
    }, 0);
  } else if (scroll_pos < animation_begin_pos) {
    el.animate({
      backgroundColor: beginning_color
    }, 0);
  } else {}

};

$(function() {
  pageInit();
  $(document).scroll(ChangeColorOnScroll);
  $(window).resize(pageInit);
});

如果有人还能在滚动时帮助我更改文本的颜色,那将是一个很好的额外功能

1 个答案:

答案 0 :(得分:1)

您可以在animation_end_pos中添加偏移量以完成所需的操作

scroll_pos = scroll;
  var animation_begin_pos = sectionsYStart[z]; //where you want the 
animation to begin
  var animation_end_pos = sectionsYStart[z + 1] - $(window).height() - 50; 
//where you want the animation to stop
  console.log($(window).height() - 50);