Is there a callback for window.scrollTo?

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

    Other answers didn't fully work for me, therefore based on @Fabian von Ellerts answer, I wrote my own solution.

    My problems were that :

    • The element I was scrolling (and all its parents along the hierarchy) always had a offsetTop of 0, so it was not working.

    • I needed to scroll a nested element.

    Using getBoundingClientRect and a container element as reference works :

        const smoothScrollTo = (
            scrollContainer,
            scrolledContent,
            offset,
            callback
        ) => {
            const fixedOffset = (
                scrollContainer.getBoundingClientRect().top + offset
            ).toFixed()
            const onScroll = () => {
                if (
                    scrolledContent.getBoundingClientRect().top.toFixed() ===
                    fixedOffset
                ) {
                    scrollContainer.removeEventListener('scroll', onScroll)
                    callback()
                }
            }
            scrollContainer.addEventListener('scroll', onScroll)
            onScroll()
            scrollContainer.scrollTo({
                top: offset,
                behavior: 'smooth',
            })
        }
    

提交回复
热议问题