像jQuery的animate scrollTop一样重复滚动

如何使用jQuery的动画scrollTop动画制作重复的scrollBy调用更流畅?

目前它是跳跃的,页面跳转到不同的滚动位置。 我怎样才能让它更顺畅?

这是scrollBy代码:

window.scrollBy(0, -10*(scrollCount ? scrollCount<0 ? -1 : 1 : 0)) , 600*x); })(i); 

这是包含它的for循环:

 for(var i = 0; i < Math.abs(scrollCount); i++){ (function(x){ setTimeout( window.scrollBy(0, -10*(scrollCount ? scrollCount<0 ? -1 : 1 : 0)) , 600*x); })(i); } } 

尝试使用这样的动画

$(’html,body’)。animate({scrollTop:currentoffset},400);

用法

首先将其添加到您的页面。

 scrollByAnimated = function(scrollY, duration){ var startTime = new Date().getTime(); var startY = window.scrollY; var endY = startY + scrollY; var currentY = startY; var directionY = scrollY > 0 ? 'down' : 'up'; var animationComplete; var count = 0; var animationId; if(duration === undefined){ duration = 250;//ms } //grab scroll events from the browser var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x //stop the current animation if its still going on an input from the user var cancelAnimation = function () { if(animationId!==undefined){ window.cancelAnimationFrame(animationId) animationId=undefined; } } if (document.attachEvent) { //if IE (and Opera depending on user setting) document.attachEvent("on"+mousewheelevt, cancelAnimation) } else if (document.addEventListener) { //WC3 browsers document.addEventListener(mousewheelevt, cancelAnimation, false) } var step = function (a,b,c) { var now = new Date().getTime(); var completeness = (now - startTime) / duration; window.scrollTo(0, Math.round(startY + completeness * scrollY)); currentY = window.scrollY; if(directionY === 'up') { if (currentY === 0){ animationComplete = true; }else{ animationComplete = currentY<=endY; } } if(directionY === 'down') { /*limitY is cross browser, we want the largest of these values*/ var limitY = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); if(currentY + window.innerHeight === limitY){ animationComplete = true; }else{ animationComplete = currentY>=endY; } } if(animationComplete===true){ /*Stop animation*/ return; }else{ /*repeat animation*/ if(count > 500){ return; }else{ count++; animationId = window.requestAnimationFrame(step); } } }; /*start animation*/ step(); }; 

然后用它;

 scrollByAnimated(100, 250);// change in scroll Y, duration in ms 

说明

这是一个比您需要的原始代码更强大的版本。 其他function包括在页面顶部和底部停止滚动,使用requestAnimationFrame()

它也只支持向上和向下滚动,因为这是我目前所需要的。 如果你向左右添加它,你将是一个很酷,很酷的人。

它仅在Chrome中进行了测试,因此您的milage可能会有所不同。

此代码利用requestAnimationFrame() 。 首先scrollByAnimated()设置变量,然后运行step() ,循环直到达到持续时间。

在每个帧中,它将动画的completeness计算为0到1之间的数字。这是startTimenow之间的差异除以duration

然后将此completeness值乘以请求的scrollY 。 这给了我们滚动每帧的数量。 然后我们添加startY位置来实现一个值,我们可以使用window.scrollTo()来设置帧的位置,而不是增加当前位置。