滚动浏览元素时更改固定标题的背景

时间:2014-02-13 14:36:06

标签: javascript jquery css background-color

我试图在页面上滚动某些DIV部分时更改固定标题的背景颜色,类似于:

http://www.adamrudzki.com/

我正在使用的部分没有固定的高度。

我发现了类似的问题Change background-color while scrolling

(使用这个小提琴http://jsfiddle.net/cEvJk/18/

var t = $('#about').offset().top - 100;

$(document).scroll(function(){
    if($(this).scrollTop() > t)
    {   
        $('header').css({"background-color":"green"});
    } 
});

但是我无法为所有部分重复效果。

3 个答案:

答案 0 :(得分:5)

试试这个:

var t = $('#about').offset().top - 100;
var t1 = $('#work').offset().top - 100;

$(document).scroll(function(){
    if($(this).scrollTop() > t1) {   
        $('header').css({"background-color":"blue"});
    } else if($(this).scrollTop() > t) {   
        $('header').css({"background-color":"green"});
    } else {
        $('header').css({"background-color":"#520833"});
    }
});

var t2 = ...

不要忘记在if

之上加上更高的值

答案 1 :(得分:5)

您可以使用jQuery's .each() method这样简化一些事情:

<强> Working Example

$(window).scroll(function () {
    $('.sect').each(function () {
        var w = $(window).scrollTop();
        var t = $(this).offset().top - 100;
        if (w > t) {
            $('header').css({
                "background-color": $(this).css('background-color')
            });
        }
    });
});

来自documentation

  

.each()方法旨在使DOM循环结构简洁   并且不易出错。调用时,它遍历DOM元素   这是jQuery对象的一部分。每次回调运行时,它都是   从0开始传递当前循环迭代。更重要的是,   回调是在当前DOM元素的上下文中触发的,所以   关键字this指的是元素。

答案 2 :(得分:0)

好的,所以我想出了THIS FIDDLE

$(document).scroll(function () {
    var x = $(this).scrollTop(),
        home = $('#home'),
        about = $('#about'),
        work = $('#work'),
        contact = $('#contact');

    if (x >= home.offset().top && x < (home.offset().top + home.height())) {
        $('header').css("background-color", "red");
    }
    if (x >= about.offset().top && x < (about.offset().top + about.height())) {
        $('header').css("background-color", "green");
    }
    if (x >= work.offset().top && x < (work.offset().top + work.height())) {

        $('header').css("background-color", "blue");
    }
    if (x >= contact.offset().top && x < (contact.offset().top + contact.height())) {
        $('header').css("background-color", "orange");
    }
});