我正在尝试创建一个脚本,当我滚动鼠标时,该脚本会自动将页面滚动到特定元素,但由于某种原因,我的动画会重复播放并且滚动来回滚动。
编辑: 我想指出,如果页面滚动到页面上的最后一个元素,则不会发生这种情况,但如果它滚动到第二个元素,它会立即反弹回顶部。
这是我的jQuery:
$(document).ready(function(){
comp = 0;
current_scroll_position = $(window).scrollTop();
console.log("CURRENT SCROLL POSITION = " +current_scroll_position);
second = $("#second").offset().top;
$(window).scroll(function(scroll_action){
$('body').on({
'mousewheel': function(e) {
e.preventDefault();
e.stopPropagation();
}
});
if(comp==0){
console.log("COMP =" +comp);
comp++;
new_scroll_position = $(window).scrollTop();
console.log("YOU SCROLLED, NEW CURRENT POSITION IS :" +new_scroll_position);
if (new_scroll_position > current_scroll_position){ //scroll going down
console.log(new_scroll_position +" > "+ current_scroll_position +" GOING DOWN");
$('body').animate({
scrollTop: second
}, 500,
function(){ //callback function for completed animation
completed_animation_scroll = true;
current_scroll_position = $(window).scrollTop();
console.log(" ANIMATING ");
console.log("CURRENT SCROLL POSITION = " +current_scroll_position);
console.log("NEW SCROLL POSITION = " +new_scroll_position);
console.log("ANIMATION COMPLETED = " +completed_animation_scroll);
console.log(" ******************* ************************ ******************");
$('body').unbind('mousewheel');
comp = 0;
});
}
else{
console.log(new_scroll_position +" > "+ current_scroll_position +" GOING DOWN");
$('body').animate({
scrollTop: 0
}, 500,
function(){ //callback function for completed animation
completed_animation_scroll = true;
current_scroll_position = $(window).scrollTop();
console.log(" ANIMATING ");
console.log("CURRENT SCROLL POSITION = " +current_scroll_position);
console.log("NEW SCROLL POSITION = " +new_scroll_position);
console.log("ANIMATION COMPLETED = " +completed_animation_scroll);
console.log(" ******************* ************************ ******************");
$('body').unbind('mousewheel');
comp = 0;
});
}
}
});
});
答案 0 :(得分:1)
问题实际上是当滚动动画完成(包括成功回调)时,$(window).scroll
处理程序被触发并再次起作用(因为滚动动画实际上是滚动而comp
等于{{1 }})。
修复它的最简单方法是使用0
将comp = 0
包裹在滚动动画回调函数中(我将setTimeout
变量的类型更改为bool):
comp
还有一些"不好的东西"比如绑定setTimeout
(
function()
{
comp = false;
},
100
);
事件处理程序但不解除绑定(如果mousewheel
不等于comp
),请查看updated fiddle以解决代码中的此类问题。< / p>
完整代码:
0