簡體   English   中英

使用緩動功能滾動

[英]Scrolling with an easing function

我編寫了一個函數,該函數在調用時將以平滑的方式向下滾動頁面。

問題是滾動量不精確。 它可以偏移一個像素左右,具體取決於滾動的距離和滾動的持續時間。

有沒有更好的方法可以做到這一點,從而使滾動條可以移動所需像素的確切數量?

 const EASING = BezierEasing(0, .1, .1, 1); // Example values. const DURATION = 1000; // ms. document.addEventListener('DOMContentLoaded', () => { document.querySelector('#foo') .addEventListener('click', onClick, false); }); function onClick(e) { scroll(400); // px. e.preventDefault(); return false; } function scroll(distance) { var start, travelled, html; start = performance.now(); travelled = 0; html = document.querySelector('html'); (function move(now) { var fractionDone, dy, toMove; fractionDone = (now-start) / DURATION; if((1 - fractionDone) <= 0) { return; // Done! } if(window.scrollY + window.innerHeight === html.offsetHeight) { return; // At bottom of page. } dy = ((EASING.get(fractionDone)) * distance); toMove = Math.floor((dy - travelled)); // `scrollBy` only accepts integers. if(toMove > 0) { window.scrollBy(0, toMove); travelled += toMove; } requestAnimationFrame(move); }(start)); } 
 <!DOCTYPE html> <html> <head> <script src="https://rawgit.com/gre/bezier-easing/master/build.js"></script> </head> <body> <a href id="foo">Click Me!</a> <script> /* print some numbers to the DOM to help visualize the scrolling */ var body = document.querySelector('body'); for(var x = 0; x < 50; x++) { var div = document.createElement("div"); var text = document.createTextNode(x); div.appendChild(text); body.appendChild(div); } </script> </body> </html> 

您能做這樣的事情來說明上一次迭代嗎?

基本上,如果toMove向下取整為0,但是距離尚未移動,是否要強制它再滾動一遍?

if(toMove > 0 || (toMove == 0 && travelled != distance) {
  window.scrollBy(0, (toMove ? toMove : 1));
  travelled += toMove;
}

我決定修改完成的邏輯以移動任何剩余距離:

// ...
if((1 - fractionDone) <= 0) {
  window.scrollBy(0, (distance - travelled)); // Scroll any remaining distance.
  return; // Done!
}
// ...

我認為,這可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM