如何滚动到另一个页面上的 ID/锚点?

问题描述 投票:0回答:2

我的导航中有一个链接,单击该链接后,会将您定向到主页并通过 id 向下滚动到特定部分。当我单击链接调用函数时,它将定向到新页面,但不会滚动到任何地方。由于该函数必须是异步的,因此它不会执行我想要执行的操作。

我的 HTML

<a id="categoryButton"><li>Categories</li></a>
<!-- further down the page -->
<div id="categoryTitleDiv"><h1 id="categoryTitle">Where I want to scroll to</h1></div>

我的JS

document.getElementById("categoryButton").onclick = function onCategoryButtonClick() {
    window.location.href = "</*my page address*/";
      document.getElementById("categoryTitleDiv").scrollIntoView();
    }

这样做的问题是,由于它们是同步的,所以命令同时发生。所以我最终从

window.location.href = "</*my page address*/";
进入了正确的页面,但我没有滚动到任何地方。

然后我尝试了解 Promise,但我不确定我做得对吗。我真的认为这会起作用,但它只会让我遇到和以前一样的问题。它们似乎仍然同步运行,我将进入新页面。

document.getElementById("categoryButton").onclick = function() {
  const promise = new Promise(function onCategoryButtonClick(resolve, reject) {
    const clickedVar = true;
    if (clickedVar) {
      window.location.href = "/*my page address*/";
      console.log("yay");
      resolve();
    } else {
      console.log("nay");
      reject();
    }
  });

  promise.then(function(){
    document.getElementById("categoryTitleDiv").scrollIntoView();
  }, function(){
    console.log("What the heck happened?");
  });
}

我也测试了其他一些东西,例如 setTimeout (尽管这并不理想),但这也不起作用。我认为是因为它想滚动到原始页面的一部分而不是新加载的页面。但我不太擅长 Javascript,所以我可能错了。我尝试的另一件事是调用 window.onload 函数并使用它来执行滚动代码,但这给我留下了与其他人相同的结果,我将其转到页面,但它滚动不到任何地方。这是代码

  window.location.href = "/*my page address*/";
  window.onload = function(){
    document.getElementById("categoryTitleDiv").scrollIntoView();
  }
}

总的来说,我非常沮丧,我一生都无法弄清楚这一点。谢谢大家,注意安全!

javascript asynchronous promise hyperlink onload
2个回答
1
投票

我尝试使用链接中的哈希实现到另一个页面上特定部分的导航:( ... / {article.link } # {article.id } )。

为了实现此目的,我需要使用 getBoundingClientRect() 方法,该方法返回一个 DOMRect 对象,提供有关所需元素相对于视口的位置的信息。

但是,如果目标页面上有大量内容,则 getBoundingClientRect() 的执行速度快于内容加载速度,导致滚动无法到达预期部分。

最后,我通过向 getBoundingClientRect() 和滚动到元素添加超时来解决这个问题。

 useEffect(() => {
    if (articles.length === 0) return;  // Wait for the articles to load
    const hash = window.location.hash.substring(1); // Extract the hash from the path
    const scrollElement = document.getElementById(hash);
    if (scrollElement) {
      setTimeout(()=>{            //(1)
        const { top } = scrollElement.getBoundingClientRect();
             setTimeout(() => {   //(2)
        window.scrollTo({
          behavior: 'smooth',
          top: top + (window.scrollY || document.documentElement.scrollTop) - 100,
        });
      }, 300); //(2) Add delay for scrolling
      }, 300); //(1) Add delay for obtaining getBoundingClientRect
    }
  }, [articles]);

0
投票

在从https://stackoverflow.com/users/3478010/roamer-1888的评论推动正确的方向后,我已经弄清楚了。我刚刚将链接的

href
转到所需页面,并将“#categoryTitleDiv”添加到网址末尾。所以看起来像

<a href="...\website name\index.html#categoryTitleDiv"><li>Categories</li></a>
滚动不流畅,但可以用!

© www.soinside.com 2019 - 2024. All rights reserved.