質問

I'm trying to get the background-color of my fixed header to change upon scrolling over certain DIV sections on the page, similar to this:

http://www.adamrudzki.com/

The sections I'm using don't have a fixed height.

I've found this similar question Change background-color while scrolling

( which uses this fiddle http://jsfiddle.net/cEvJk/18/ )

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

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

But I'm unable to get the effect to repeat for all sections.

役に立ちましたか?

解決

Try this :

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"});
    }
});

And so on with var t2 = ....

Don't forget to put higher values on top of the if's

他のヒント

You could simplify things a bit by using jQuery's .each() method like this:

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')
            });
        }
    });
});

From the documentation:

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Okay so I came up with 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");
    }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top