看这里: http://jsfiddle.net/1L5y559z/
假设当有人滚动到div 1之下或之下时,我想改变身体的背景颜色,如果可以,我将如何使用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做同样的事情。
答案 0 :(得分:12)
这是同样的事情。你只需要确定div的顶部离窗口顶部有多远。然后确定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');
}
});
});
看到这个小提琴:http://jsfiddle.net/5d922roc/
答案 1 :(得分:0)
您可以简单地获取div元素的偏移量并使用它来替换测试偏移位置。看看http://api.jquery.com/offset/:)