UPD:我创建了一个npm软件包,该软件包比以下解决方案更好,并且更易于使用。
我的smoothScroll函数
我采用了史蒂夫·班顿(Steve Banton)的出色解决方案,并编写了一个使使用起来更加方便的函数。就像我之前尝试过的那样,使用window.scroll()或什至会更容易window.scrollBy(),但是这两个存在一些问题:  
- 使用它们后,一切都会变得很混乱。
- 您无论如何都无法阻止它们,而必须等到滚动条的和为止。因此,我希望我的功能对您有用。此外,还有一个轻量级的polyfill,使其可以在Safari甚至IE中运行。  
这是代码
只需复制它,然后将其弄乱就可以了。
import smoothscroll from 'smoothscroll-polyfill';
smoothscroll.polyfill();
const prepareSmoothScroll = linkEl => {
  const EXTRA_OFFSET = 0;
  const destinationEl = document.getElementById(linkEl.dataset.smoothScrollTo);
  const blockOption = linkEl.dataset.smoothScrollBlock || 'start';
  if ((blockOption === 'start' || blockOption === 'end') && EXTRA_OFFSET) {
    const anchorEl = document.createElement('div');
    destinationEl.setAttribute('style', 'position: relative;');
    anchorEl.setAttribute('style', `position: absolute; top: -${EXTRA_OFFSET}px; left: 0;`);
    destinationEl.appendChild(anchorEl);
    linkEl.addEventListener('click', () => {
      anchorEl.scrollIntoView({
        block: blockOption,
        behavior: 'smooth',
      });
    });
  }
  if (blockOption === 'center' || !EXTRA_OFFSET) {
    linkEl.addEventListener('click', () => {
      destinationEl.scrollIntoView({
        block: blockOption,
        behavior: 'smooth',
      });
    });
  }
};
export const activateSmoothScroll = () => {
  const linkEls = [...document.querySelectorAll('[data-smooth-scroll-to]')];
  linkEls.forEach(linkEl => prepareSmoothScroll(linkEl));
};
要创建链接元素,只需添加以下数据属性:
data-smooth-scroll-to="element-id"
您也可以将另一个属性设置为加法
data-smooth-scroll-block="center"
它代表功能的block选项scrollIntoView()。默认情况下为start。阅读有关MDN的更多信息。
最后
根据需要调整smoothScroll功能。
例如,如果您有一些固定的标头(或者用单词来称呼它masthead),则可以执行以下操作:
const mastheadEl = document.querySelector(someMastheadSelector);
// and add it's height to the EXTRA_OFFSET variable
const EXTRA_OFFSET = mastheadEl.offsetHeight - 3;
如果您没有这种情况,请删除它,为什么不:-D。
               
              
scrollIntoView。