fix: use native smooth scroll when possible (#751)

This commit is contained in:
Nolan Lawson 2018-12-07 08:20:16 -08:00 committed by GitHub
parent 2280ff2832
commit 4b028b1a62
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 3 deletions

View file

@ -2,7 +2,7 @@
const easingOutQuint = (x, t, b, c, d) => const easingOutQuint = (x, t, b, c, d) =>
c * ((t = t / d - 1) * t * t * t * t + 1) + b c * ((t = t / d - 1) * t * t * t * t + 1) + b
const scroll = (node, key, target) => { function smoothScrollPolyfill (node, key, target) {
const startTime = Date.now() const startTime = Date.now()
const offset = node[key] const offset = node[key]
const gap = target - offset const gap = target - offset
@ -44,4 +44,32 @@ const scroll = (node, key, target) => {
return cancel return cancel
} }
export const smoothScrollToTop = node => scroll(node, 'scrollTop', 0) function testSupportsSmoothScroll () {
let supports = false
try {
let div = document.createElement('div')
div.scrollTo({
top: 0,
get behavior () {
supports = true
return 'smooth'
}
})
} catch (err) {} // Edge throws an error
return supports
}
const smoothScrollSupported = process.browser && testSupportsSmoothScroll()
export function smoothScrollToTop (node) {
if (smoothScrollSupported) {
console.log('using native smooth scroll')
return node.scrollTo({
top: 0,
behavior: 'smooth'
})
} else {
console.log('using polyfilled smooth scroll')
return smoothScrollPolyfill(node, 'scrollTop', 0)
}
}