smooth scroll to top

前端 未结 12 1216
眼角桃花
眼角桃花 2020-12-07 22:58

I\'ve bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors

12条回答
  •  悲&欢浪女
    2020-12-07 23:28

    Some time has passed since this was asked.

    Now it is possible to not only specify number to window.scroll function, but also pass an object with three properties: top, left and behavior. So if we would like to have a smooth scroll up with native JavaScript, we can now do something like this:

    let button = document.querySelector('button-id');
    let options = {top: 0, left: 0, behavior: 'smooth'}; // left and top are coordinates
    button.addEventListener('click', () => { window.scroll(options) });
    

    https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

提交回复
热议问题