Smooth scroll anchor links WITHOUT jQuery

前端 未结 14 1939
暗喜
暗喜 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:55

    Vanilla js variant using requestAnimationFrame with easings and all browsers supported:

    const requestAnimationFrame = window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame;
    
    function scrollTo(to) {
        const start = window.scrollY || window.pageYOffset
        const time = Date.now()
        const duration = Math.abs(start - to) / 3;
    
        (function step() {
            var dx = Math.min(1, (Date.now() - time) / duration)
            var pos = start + (to - start) * easeOutQuart(dx)
    
            window.scrollTo(0, pos)
    
            if (dx < 1) {
                requestAnimationFrame(step)
            }
        })()
    }
    

    Any easing supported!

提交回复
热议问题