[英]Make repeated scrollBy smoother like jQuery's animate scrollTop
我怎樣才能使重復的scrollBy調用變得更平滑,就像使用jQuery的動畫scrollTop進行動畫處理時一樣?
當前它是跳躍的,頁面在不同的滾動位置之間來回跳轉。 如何使它更平滑?
這是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
說明
這是比原始代碼建議的功能更強大的版本。 其他功能包括在頁面頂部和底部停止滾動,使用requestAnimationFrame()
。
它還僅支持上下滾動,因為這就是我目前所需要的。 如果在左右添加,您將是一個很酷的人。
它僅在Chrome中經過測試,因此里程可能會有所不同。
此代碼利用了requestAnimationFrame()
。 首先, scrollByAnimated()
設置變量,然后運行step()
,直到達到持續時間為止,該step()
一直循環。
在每幀中,它以0到1之間的數字來計算動畫的completeness
。這是startTime
與now
之間的差,再除以duration
。
然后將此completeness
值乘以請求的scrollY
。 這使我們可以滾動每一幀。 然后,我們添加startY
位置以獲取一個值,我們可以使用window.scrollTo()
設置框架的位置,而不是增加當前位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.