yyt
8 天以前 0cceb649e1dc443c2a91d26d81eacb0867c96db3
提交 | 用户 | 时间
0cceb6 1 Math.easeInOutQuad = function(t, b, c, d) {
Y 2   t /= d / 2
3   if (t < 1) {
4     return c / 2 * t * t + b
5   }
6   t--
7   return -c / 2 * (t * (t - 2) - 1) + b
8 }
9
10 // requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
11 var requestAnimFrame = (function() {
12   return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
13 })()
14
15 /**
16  * Because it's so fucking difficult to detect the scrolling element, just move them all
17  * @param {number} amount
18  */
19 function move(amount) {
20   document.documentElement.scrollTop = amount
21   document.body.parentNode.scrollTop = amount
22   document.body.scrollTop = amount
23 }
24
25 function position() {
26   return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
27 }
28
29 /**
30  * @param {number} to
31  * @param {number} duration
32  * @param {Function} callback
33  */
34 export function scrollTo(to, duration, callback) {
35   const start = position()
36   const change = to - start
37   const increment = 20
38   let currentTime = 0
39   duration = (typeof (duration) === 'undefined') ? 500 : duration
40   var animateScroll = function() {
41     // increment the time
42     currentTime += increment
43     // find the value with the quadratic in-out easing function
44     var val = Math.easeInOutQuad(currentTime, start, change, duration)
45     // move the document.body
46     move(val)
47     // do the animation unless its over
48     if (currentTime < duration) {
49       requestAnimFrame(animateScroll)
50     } else {
51       if (callback && typeof (callback) === 'function') {
52         // the animation is done so lets callback
53         callback()
54       }
55     }
56   }
57   animateScroll()
58 }