Smooth scroll anchor links WITHOUT jQuery

前端 未结 14 1940
暗喜
暗喜 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;
    }

提交回复
热议问题