我已经为我的照片博客实现了一个动画。但仍有一个大问题,因为“body”元素会使动画运行两次。
我想问题出在$('body').animate上。当body正在进行动画时,滚动事件会被再次激活,从而触发两次事件。
我的代码的问题是向上滚动页面。当我向上滚动页面时,scrollAnimatePrev会被触发,然后$('body')元素会开始运动。动画结束后,animating变量被设置为false。但是$('body')元素会再次触发滚动事件,因为当我设置scrollTop时,滚动事件就会被触发。所以当前位置currentPos再次被设置为$(window).scrollTop(),然后currentPos > previousPos返回true并且 !animating返回true,所以它将触发scrollAnimate。
现在我想修复这个问题,怎么办?
我想问题出在$('body').animate上。当body正在进行动画时,滚动事件会被再次激活,从而触发两次事件。
我的代码的问题是向上滚动页面。当我向上滚动页面时,scrollAnimatePrev会被触发,然后$('body')元素会开始运动。动画结束后,animating变量被设置为false。但是$('body')元素会再次触发滚动事件,因为当我设置scrollTop时,滚动事件就会被触发。所以当前位置currentPos再次被设置为$(window).scrollTop(),然后currentPos > previousPos返回true并且 !animating返回true,所以它将触发scrollAnimate。
现在我想修复这个问题,怎么办?
$(function() {
var record = 0;
var imgHeight = $(".images").height();
var offset = $(".images").eq(0).offset();
var offsetHeight = offset.top;
var previousPos = $(window).scrollTop();
var animating = false;
var state = 0;
$(window).scroll(function() {
var currentPos = $(window).scrollTop();
console.log(currentPos);
if(currentPos > previousPos && !animating) {
record++;
scrollAnimate(record, imgHeight, offsetHeight);
animating = true;
} else if (currentPos < previousPos && !animating) {
record--
scrollAnimatePrev(record, imgHeight, offsetHeight);
animating = true;
}
previousPos = currentPos;
console.log(previousPos)
})
function scrollAnimate(record, imgHeight, offsetHeight) {
$('body').animate(
{scrollTop: (parseInt(offsetHeight) * (record+1)) + (parseInt(imgHeight) * record)},
1000,
"easeInOutQuart"
)
.animate(
{scrollTop: (parseInt(offsetHeight) * (record)) + (parseInt(imgHeight) * (record))},
1000,
"easeOutBounce",
function() {
animating = false;
}
)
}
function scrollAnimatePrev(record, imgHeight, offsetHeight) {
$('body').animate(
{scrollTop: ((parseInt(imgHeight) * record) + (parseInt(offsetHeight) * record)) - offsetHeight},
1000,
"easeInOutQuart"
)
.animate(
{scrollTop: ((parseInt(imgHeight) * record) + (parseInt(offsetHeight) * record))},
1000,
"easeOutBounce",
function() {
animating = false;
}
)
}
})