Smooth scroll anchor links WITHOUT jQuery

前端 未结 14 1921
暗喜
暗喜 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"
        })
    }
    
    0 讨论(0)
  • 2020-11-30 20:46

    Use this:

    let element = document.getElementById("box");
    
    element.scrollIntoView();
    element.scrollIntoView(false);
    element.scrollIntoView({block: "end"});
    element.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"});
    

    DEMO: https://jsfiddle.net/anderpo/x8ucc5ak/1/

    0 讨论(0)
  • 2020-11-30 20:48

    Here is a simple solution in pure JavaScript. It takes advantage of CSS property scroll-behavior: smooth

    function scroll_to(id) {       
        document.documentElement.style.scrollBehavior = 'smooth'
        element = document.createElement('a');
        element.setAttribute('href', id)
        element.click();
    }
    

    Usage:

    Say we have 10 divs:

    <div id='df7ds89' class='my_div'>ONE</div>
    <div id='sdofo8f' class='my_div'>TWO</div>
    <div id='34kj434' class='my_div'>THREE</div>
    <div id='gbgfh98' class='my_div'>FOUR</div>
    <div id='df89sdd' class='my_div'>FIVE</div>
    <div id='34l3j3r' class='my_div'>SIX</div>
    <div id='56j5453' class='my_div'>SEVEN</div>
    <div id='75j6h4r' class='my_div'>EIGHT</div>
    <div id='657kh54' class='my_div'>NINE</div>
    <div id='43kjhjh' class='my_div'>TEN</div>
    

    We can scroll to the ID of choice:

    scroll_to('#657kh54')
    

    You simply call this function on your click event (e.g. click button then scroll to div #9).

    Result:

    Of course it looks much smoother in real life.

    FIDDLE

    Unfortunately, IE and Safari don't support scrollBehavior = 'smooth' as of 2019

    MDN Web Docs

    0 讨论(0)
  • 2020-11-30 20:49

    Extending this answer: https://stackoverflow.com/a/8918062/3851798

    After defining your function of scrollTo, you can pass the element you want to scrollTo in the function.

    function scrollTo(element, to, duration) {
        if (duration <= 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 10;
    
        setTimeout(function() {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) return;
            scrollTo(element, to, duration - 10);
        }, 10);
    }
    

    If you have a div with an id="footer"

    <div id="footer" class="categories">…</div>
    

    In the script that you run to scroll you can run this,

    elmnt = document.getElementById("footer");
    scrollTo(document.body, elmnt.offsetTop, 600);
    

    And there you have it. Smooth scrolling without jQuery. You can actually play around with that code on your browser's console and fine tune it to your liking.

    0 讨论(0)
  • 2020-11-30 20:50

    Using the function from here: JavaScript animation and modifying it to modify a property (not only a style's property), you can try something like this:

    function animate(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);
                if (prop) {
                    elem[style] = (from + step * (to - from))+unit;
                } else {
                    elem.style[style] = (from + step * (to - from))+unit;
                }
                if (step === 1) {
                    clearInterval(timer);
                }
            }, 25);
        if (prop) {
              elem[style] = from+unit;
        } else {
              elem.style[style] = from+unit;
        }
    }
    
    window.onload = function () {
        var target = document.getElementById("div5");
        animate(document.scrollingElement || document.documentElement, "scrollTop", "", 0, target.offsetTop, 2000, true);
    };
    

    DEMO: https://jsfiddle.net/zpu16nen/

    Make sure you size the window small enough so there's actually a scrollbar and can scroll to the 5th div.

    And no, it didn't require the recreation of 25% of jQuery.

    This would obviously needly highly modified depending on what your question actually means (like when the window hash changes, or something like that).

    Note that with jQuery, it's as easy as:

    $(document).ready(function () {
        $("html, body").animate({
            scrollTop: $("#div5").offset().top
        }, 2000);
    });
    

    DEMO: http://jsfiddle.net/7TAa2/1/

    Just saying...

    0 讨论(0)
  • 2020-11-30 20:50

    CSS3 transitions with a :target selector can give a nice result without any JS hacking. I was just contemplating whether to imlement this but without Jquery it does get a bit messy. See this question for details.

    0 讨论(0)
提交回复
热议问题