iPhone / iPad:Vanilla JS scrollTop无法在Chrome上运行

时间:2019-05-07 08:50:35

标签: javascript html css

Vue CLI 3,Vue 2.5.17

当RestApi响应成功时,我想滚动到“特定div元素”。但是我的代码不适用于IOS设备。

我尝试使用“ scroll”,“ scrollTo”和“ scrollTop”功能。但是这些功能不起作用。

 const el = document.querySelector(selector)

 // Custom Scroll Class Method
 Scroll.scrollIt(el, 200, 'linear')

 // Common ScrollTo Method
 document.querySelector('html', 'body')
   .scrollTo({
     top: (el.offsetTop - 90),
     left: 0,
     behavior: 'smooth'
   })

ScrollIt函数是自定义Scroll类方法。

export default class Scroll {
  public static scrollIt (element: HTMLElement, duration: number, callback?: Function) {
    const start = document.querySelector('document, html, body').scrollTop
    const change = element.offsetTop - start
    let currentTime = 0
    const increment = 20

    const animateScroll = function () {
      currentTime += increment
      const val = easeInOutQuad(currentTime, start, change, duration)
      document.querySelector('document, html, body').scrollTop = val - 90
      if (currentTime < duration) {
        setTimeout(animateScroll, increment)
      }
    }
    animateScroll()

    // t = current time
    // b = start value
    // c = change in value
    // d = duration
    function easeInOutQuad (t: number, b: number, c: number, d: number) {
      t /= d/2
      if (t < 1) return c/2*t*t + b
      t--
      return -c/2 * (t*(t-2) - 1) + b
    }
  }
}

0 个答案:

没有答案