-
Notifications
You must be signed in to change notification settings - Fork 47
/
scrollApi.js
48 lines (43 loc) · 1.39 KB
/
scrollApi.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
40
41
42
43
44
45
46
47
48
/**
* @desc scroll滚动方法
|*| * scrollApi.getScrollTop()
|*| * scrollApi.setScrollTop(h)
|*| * scrollApi.scrollTo(to,duration)
*/
var requestAnimationFrame = function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
}();
var scrollApi = {
getScrollTop: function getScrollTop() {
return document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
},
setScrollTop: function setScrollTop(h) {
h && window.scrollTo(0, h);
},
scrollTo: function scrollTo(to) {
var _this = this;
var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var minDecelerate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
var diff = to - this.getScrollTop();
if (diff === 0) return;
if (duration <= 0) {
this.setScrollTop(to);
return;
}
var step = diff / duration * 10;
requestAnimationFrame(function () {
if (Math.abs(step) > Math.abs(diff)) {
_this.setScrollTop(_this.getScrollTop() + diff);
return;
}
_this.setScrollTop(_this.getScrollTop() + step);
if (diff > 0 && _this.getScrollTop() >= to || diff < 0 && _this.getScrollTop() <= to) {
return;
}
_this.scrollTo(to, duration - 16 / minDecelerate);
});
}
};
module.exports = scrollApi;