Smooth scroll anchor links WITHOUT jQuery

2019-01-13 02:51发布

问题:

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.

回答1:

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...



回答2:

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.



回答3:

Actually, there is more lightweight and simple way to do that: https://codepen.io/ugg0t/pen/mqBBBY

function scrollTo(element) {
  window.scroll({
    behavior: 'smooth',
    left: 0,
    top: element.offsetTop
  });
}

document.getElementById("button").addEventListener('click', () => {
  scrollTo(document.getElementById("8"));
});
div {
  width: 100%;
  height: 200px;
  background-color: black;
}

div:nth-child(odd) {
  background-color: white;
}

button {
  position: absolute;
  left: 10px;
  top: 10px;
}
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>
<button id="button">Button</button>



回答4:

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.



回答5:

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/



回答6:

Pure lightweight javascript library: smooth-scroll on github



回答7:

My favorite scroll-to library currently is Zenscroll because of the wide range of features and small size (currently only 3.17kb).

In the future it may make more sense to use the native scrollIntoView functionality, but since it'd have to be polyfilled in most production sites today due to the lack of IE support, I recommend using Zenscroll instead in all cases.



回答8:

you can use this javascript Library to add smooth scrolling to all your internal links. You may add configuration also, to provide links to ignore. You may have a detailed look here. https://codingninjascodes.github.io/SmoothScrollJs/



回答9:

Smooth Scroll behavior with polyfill...

Example:

document.querySelectorAll('a[href^="#"]').addEventListener('click', function(e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' });
});

Repository: https://github.com/iamdustan/smoothscroll