Is there a callback for window.scrollTo?

前端 未结 3 1090
无人及你
无人及你 2020-12-15 16:32

I want to call focus() on an input after the widow scrolled. I\'m using the smooth behavior for the scrollTo() method. The problem is the foc

3条回答
  •  鱼传尺愫
    2020-12-15 17:18

    I found a way to achieve what I want but I think it's a bit hacky, isn't it?

    let el = document.getElementById('input')
    let elScrollOffset = el.getBoundingClientRect().top
    let scrollOffset = window.pageYOffset || document.documentElement.scrollTop
    let padding = 12
    let target = elScrollOffset + scrollOffset - padding
    window.scrollTo({
      top: target,
      behavior: 'smooth'
    })
    window.onscroll = e => {
      let currentScrollOffset = window.pageYOffset || document.documentElement.scrollTop
      // Scroll reach the target
      if (currentScrollOffset === target) {
        el.focus()
        window.onscroll = null // remove listener
      }
    }
    

提交回复
热议问题