我正在尝试制作一个脚本,当我滚动鼠标时,该脚本会自动将页面滚动到特定元素,但由于某种原因,我的动画会重复并且滚动会来回移动。
编辑: 我想指出的是,如果页面滚动到页面上的最后一个元素,则不会发生这种情况,但如果滚动到第二个元素,它将立即弹回到顶部。
这是我的 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;
});
}
}
});
});
最佳答案
问题实际上是当滚动动画完成时(包括成功回调),$(window).scroll
处理程序被触发并再次工作(因为滚动动画实际上是滚动并且 comp
等于 0
)。
解决这个问题的最简单方法是使用 setTimeout
将 comp = 0
包装在滚动动画回调函数中(我更改了 comp
变量的类型 bool ):
setTimeout
(
function()
{
comp = false;
},
100
);
还有一些“不好的事情”,例如绑定(bind) mousewheel
事件处理程序但不取消绑定(bind)它(如果 comp
不等于 0
) ,所以请看一下updated fiddle修复代码中的此类问题。
完整代码:
$(document).ready(function()
{
var comp = false;
var current_scroll_position = $(window).scrollTop();
var secondOffsetTop = $("#second").offset().top;
$(window).scroll(function()
{
if (comp)
{
return;
}
comp = true;
$('body').on('mousewheel', function()
{
return false;
});
var scrollTo = 0;
if ($(window).scrollTop() > current_scroll_position)
{
scrollTo = secondOffsetTop;
}
$('body').animate
(
{
scrollTop: scrollTo
},
500,
function()
{
current_scroll_position = $(window).scrollTop();
$('body').off('mousewheel');
setTimeout
(
function()
{
comp = false;
},
100
);
}
);
});
});
关于javascript - Animate() 无法与scrollTop 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25509541/