Is there a callback for window.scrollTo?

前端 未结 3 1097
无人及你
无人及你 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:22

    I wrote a generic function based on the solution of George Abitbol, without overwriting window.onscroll:

    /**
     * Native scrollTo with callback
     * @param offset - offset to scroll to
     * @param callback - callback function
     */
    function scrollTo(offset, callback) {
        const fixedOffset = offset.toFixed(),
            onScroll = function () {
                if (window.pageYOffset.toFixed() === fixedOffset) {
                    window.removeEventListener('scroll', onScroll)
                    callback()
                }
            }
    
        window.addEventListener('scroll', onScroll)
        onScroll()
        window.scrollTo({
            top: offset,
            behavior: 'smooth'
        })
    }
    

提交回复
热议问题