Smooth scroll anchor links WITHOUT jQuery

前端 未结 14 1944
暗喜
暗喜 2020-11-30 20:06

Is it possible to use smooth scroll to anchor links but without jQuery? I am creating a new site and I don\'t want to use jQuery.<

14条回答
  •  甜味超标
    2020-11-30 20:38

    For anyone in 2019, first, you add an event listener

      document.getElementById('id').addEventListener('click', () => scrollTo())
    

    then you target the element and go smoothly to it

    function scrollTo() {
        let target = document.getElementById('target');
        target.scrollIntoView({
            behavior: "smooth", 
            block: "end", 
            inline: "nearest"
        })
    }
    

提交回复
热议问题