首先,我想说我是jQuery的新手。当用户滚动到这个位置时,我使用这个脚本来动画两个div的背景色。第一个div运行良好,但#contact无法工作,因为#contact从顶部定位为500%,所以当我向下滚动500像素时,动画就会触发。我不知道如何将其从像素更改为百分比。
我只在java的颜色部分和最新版本的jQuery中使用它。
另外,我知道这是另一个问题,但有什么方法,一旦你滚动的div返回到它的原始状态,如果用户卷动回来,动画将再次启动?
JS小提琴 http://jsfiddle.net/8SWG4/
$(窗口).scroll(函数(){) 如果($(窗口).scrollTop()> 500){ $("#contact").stop().animate({ backgroundColor:'#fff',},1000);}{${$(“约”).stop().animate({ backgroundColor:'#000',},1000);};};
发布于 2013-07-07 18:57:15
可以使用$(element).offset().top
检测到该元素的滚动传递。
示例演示:http://jsfiddle.net/yeyene/8SWG4/6/
$(window).scroll(function() {
if($(this).scrollTop() >= $("#blog").offset().top){
$("#contact").stop().animate({
backgroundColor: '#000',
}, 2000);
}
if($(this).scrollTop() <= $("#blog").offset().top){
$("#contact").stop().animate({
backgroundColor: '#fff',
}, 2000);
}
if($(this).scrollTop() >= $("#home").offset().top/2){
$("#about").stop().animate({
backgroundColor: '#000',
}, 2000);
}
if($(this).scrollTop() <= $("#home").offset().top/2){
$("#about").stop().animate({
backgroundColor: '#fff',
}, 2000);
}
});
发布于 2013-07-07 22:02:42
500%的屏幕外,将无法工作。你是说50%还是?你怎么把高度传给你的div?
无论如何,不能直接在%上触发滚动高度,但可以这样做:
var a = $(document).height();
var a3= Math.floor(a * 0.3); // 30%
var a5= Math.floor(a * 0.5); // 50%
var a8= Math.floor(a * 0.8); // 80%
我使用了$(document).height();
,但是如果您有一个包装器div,您也可以使用它,比如$('#div_id').height();
要让动画“重新启动”,当用户回滚时,检查here。你也可以做叶烯的建议,使用$(element).offset().top
。
我将您的另一个问题中的代码修改为:
$(window).scroll(function () {
a = b = c = false;
console.log($(window).scrollTop());
if ($(window).scrollTop() > 0 && $(window).scrollTop() < 400) {
a = true;
}
if ($(window).scrollTop() > 399 && $(window).scrollTop() < 900) {
b = true;
}
if ($(window).scrollTop() > 899 ) {
c = true;
}
$("#home").stop().animate({
backgroundColor: a ? '#00f' : '#fff',
}, 1000);
$("#about").stop().animate({
backgroundColor: b ? '#0f0' : '#fff',
}, 1000);
$("#contact").stop().animate({
backgroundColor: c ? '#f00' : '#fff',
}, 1000);
});
https://stackoverflow.com/questions/17518468
复制