我有以下代码,如果我使用它,滚动效果不起作用,但如果我将持续时间从500更改为50,一切都可以。
$(document).ready(function(){
currentScrollTop = $( window ).scrollTop();
$( window ).scroll( scrollWindow );
});
function scrollWindow(){
var newScrollTop = $( window ).scrollTop();
var height = $( window ).height();
if( currentScrollTop > newScrollTop ){
var newPosition = currentScrollTop - height;
$( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
currentScrollTop = $( window ).scrollTop();
});
}
else if( currentScrollTop < newScrollTop ){
var newPosition = currentScrollTop + height;
$( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
currentScrollTop = $( window ).scrollTop();
});
}
}
我摆弄here
答案 0 :(得分:2)
这里有两个问题:
1。您永远不会更新currentScrollTop
。
2. 您需要限制在页面滚动时重新触发滚动事件。您可以在动画发生时使用.off
删除事件(为了此目的,我已修改您的事件处理程序以使用.on
而非.scroll
),然后重新绑定它动画完成。
解决方案: JSFiddle(我添加了一个可调整的输入用于测试,因此您可以更改滚动速度。)
$(document).ready(function(){
currentScrollTop = $( window ).scrollTop();
$( window ).on("scroll", scrollWindow );
});
function scrollWindow(){
var newScrollTop = $( window ).scrollTop();
var height = $( window ).height();
console.log(newScrollTop);
if( currentScrollTop > newScrollTop ){
var newPosition = currentScrollTop - height;
//Remove our scroll event during animation
$(window).off();
$( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
currentScrollTop = $( window ).scrollTop();
//Rebind event after animation complete
$( window ).on("scroll", scrollWindow );
});
}
else if( currentScrollTop < newScrollTop ){
//Remove our scroll event during animation
$(window).off();
var newPosition = currentScrollTop + height;
$( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
currentScrollTop = $( window ).scrollTop();
//Rebind event after animation complete
$( window ).on("scroll", scrollWindow );
});
}
//Update scrollTop
currentScrollTop = newScrollTop();
}
答案 1 :(得分:0)
如果您在小提琴上等待一段时间,您可以看到滚动效果有效。实际上,当你的animate函数的duration参数是500时,它比它在50时相对慢。所以当你向更高的值移动时,你正在减慢滚动速度。您可以查看此文档以供参考。您还可以使用“慢”和“快”等字符串代替500或50作为动画持续时间。
http://api.jquery.com/animate/#duration
或者您可以使用超时。试试这个代码: -
$(document).ready(function(){
currentScrollTop = $( window ).scrollTop();
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
var newScrollTop = $( window ).scrollTop();
var height = $( window ).height();
if( currentScrollTop > newScrollTop ){
var newPosition = currentScrollTop - height;
$( "html, body" ).animate({ scrollTop: newPosition }, 500,
function(){
currentScrollTop = $( window ).scrollTop();
});
}
else if( currentScrollTop < newScrollTop ){
var newPosition = currentScrollTop + height;
$( "html, body" ).animate({ scrollTop: newPosition }, 500,function(){
currentScrollTop = $( window ).scrollTop();
});
}
}, 50);});});