Smooth scroll anchor links WITHOUT jQuery

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

    It's upgraded version from @Ian

    // Animated scroll with pure JS
    // duration constant in ms
    const animationDuration = 600;
    // scrollable layout
    const layout = document.querySelector('main');
    const fps = 12;  // in ms per scroll step, less value - smoother animation
    function scrollAnimate(elem, style, unit, from, to, time, prop) {
        if (!elem) {
            return;
        }
        var start = new Date().getTime(),
            timer = setInterval(function () {
                var step = Math.min(1, (new Date().getTime() - start) / time);
                var value =  (from + step * (to - from)) + unit;
                if (prop) {
                    elem[style] = value;
                } else {
                    elem.style[style] = value;
                }
                if (step === 1) {
                    clearInterval(timer);
                }
            }, fps);
        if (prop) {
            elem[style] = from + unit;
        } else {
            elem.style[style] = from + unit;
        }
    }
    
    function scrollTo(hash) {
        const target = document.getElementById(hash);
        const from = window.location.hash.substring(1) || 'start';
        const offsetFrom = document.getElementById(from).offsetTop;
        const offsetTo = target.offsetTop;
        scrollAnimate(layout,
            "scrollTop", "", offsetFrom, offsetTo, animationDuration, true);
        setTimeout(function () {
          window.location.hash = hash;
        }, animationDuration+25)
    };
    
    // add scroll when click on menu items 
    var menu_items = document.querySelectorAll('a.mdl-navigation__link');
    menu_items.forEach(function (elem) {
        elem.addEventListener("click",
            function (e) {
                e.preventDefault();
                scrollTo(elem.getAttribute('href').substring(1));
            });
    });
    
    // scroll when open link with anchor 
    window.onload = function () {
        if (window.location.hash) {
            var target = document.getElementById(window.location.hash.substring(1));
            scrollAnimate(layout, "scrollTop", "", 0, target.offsetTop, animationDuration, true);
        }
    }
    

提交回复
热议问题