当用户滚动超过或低于特定 div 时更改 css

change css when user scroll past or below a specific div

看这里: http://jsfiddle.net/1L5y559z/

假设我想在有人滚动过去或下方时更改正文的背景颜色 div1,如果可以,我该如何使用 jquery 来实现?

我知道有这个:

$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 100;

if(y_scroll_pos > scroll_pos_test) {
   $("body").css("background-color","black");
}
else
{
   $("body").css("background-color","white");
}
});

但它适用于当您滚动超过或低于特定数字像素时。我正在尝试为特定的 div 获取相同的东西。

这是一回事。您只需确定 div 的顶部距离 window 的顶部有多远。然后确定 div 的高度,将两者相加,得到与要发生变化的顶部的像素距离。然后,当您滚动到该点时,您将进行更改。

$(function(){
    $(window).scroll(function() {
        var scroll = $(window).scrollTop(); // how many pixels you've scrolled
        var os = $('#div1').offset().top; // pixels to the top of div1
        var ht = $('#div1').height(); // height of div1 in pixels
        // if you've scrolled further than the top of div1 plus it's height
        // change the color. either by adding a class or setting a css property
        if(scroll > os + ht){
            $('#div2').addClass('blue');
        }
    });
});

看到这个fiddle:http://jsfiddle.net/5d922roc/

您可以简单地获取 div 元素的偏移量并使用它来替换您的测试偏移位置。看看http://api.jquery.com/offset/ :)