1

我的 docusaurus 主页上有多个部分,从顶部导航栏中,我可以scrollTo通过检查使用以下代码来指定部分window.location.pathname==='/'

let navLink = document.querySelectorAll('nav .navbar__link');
if(navLink) {
  navLink.forEach(function(link) {
      link.addEventListener('click', function(e){
        e.preventDefault();
        let selectedSection = e.currentTarget.textContent.toLowerCase();
        if(window.location.pathname === '/') {
          window.scrollTo(0,document.querySelector(`#anchor-${selectedSection}-section`).offsetTop - 100);
        }
      })
  })
}

当我在主页上时,它工作正常。

Home通过单击导航链接从文档页面返回(路由)到主页后,该scrollTo方法不起作用,我直接路由到文档路径而不是滚动到主页部分之一。虽然我正在检查window.location.pathname === '/'代码没有执行。

有人可以帮我弄清楚从文档页面单击时路由幕后发生的事情。

注意:我已将上述脚本写入index.js文件。

4

1 回答 1

1

第 1 步:创建一个名为 home.js 的新页面

第 2 步:将 docusaurus.config.js 链接对象从更新//home

{ to: '/home', label: "Home", position: 'left'}

第 3 步:在里面home.js添加了重定向功能以重定向到“/”,这解决了我的实际问题。

于 2020-04-28T12:20:15.253 回答