-
Notifications
You must be signed in to change notification settings - Fork 592
/
scrollTo.js
39 lines (38 loc) · 1.12 KB
/
scrollTo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var getScrollTop = require('./getScrollTop');
var setScrollTop = require('./setScrollTop');
var requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
/**
*
* @desc 在${duration}时间内,滚动条平滑滚动到${to}指定位置
* @param {Number} to
* @param {Number} duration
*/
function scrollTo(to, duration) {
if (duration < 0) {
setScrollTop(to);
return
}
var diff = to - getScrollTop();
if (diff === 0) return
var step = diff / duration * 10;
requestAnimFrame(
function () {
if (Math.abs(step) > Math.abs(diff)) {
setScrollTop(getScrollTop() + diff);
return;
}
setScrollTop(getScrollTop() + step);
if (diff > 0 && getScrollTop() >= to || diff < 0 && getScrollTop() <= to) {
return;
}
scrollTo(to, duration - 16);
});
}
module.exports = scrollTo;