Smooth scroll anchor links WITHOUT jQuery

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

    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>

    0 讨论(0)
  • 2020-11-30 21:05

    Smooth Scroll behavior with polyfill...

    Example:

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

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

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