Detect when scrolling has finished when using `scroll-behavior: smooth`

前端 未结 3 828
小鲜肉
小鲜肉 2021-02-18 14:19

What is the best way to detect when scrolling to an element on the page has finished? The spec says that \"The scrolling box is scrolled in a smooth fashion using a user-agent-d

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-18 15:06

    Maybe I'm not understanding the question, but why not just detect when the element you're scrolling to has come to its final position relative to the top to the viewport...

    var scrollElem = document.querySelector('.scroll-me'),
        offsetTop = 300;
    
    window.addEventListener('scroll', checkScroll);
    document.addEventListener("DOMContentLoaded", checkScroll)
    
    function checkScroll() {
        var viewportOffset = scrollElem.getBoundingClientRect(),
            distanceToTop = viewportOffset.top;
    
        if (distanceToTop <= offsetTop) {
            callback();
        }
    }
    

提交回复
热议问题