首页 > 解决方案 > 尝试在新标签加载时滚动到目标 ID

问题描述

我正在尝试编写一个读取 URL 的函数,如果 URL 包含#,则显示跳转到id=<string following #>. 所以myurl.com/#overview应该滚动到文档元素所在的位置id='overview'

我还想在加载所有文档元素后在页面加载时运行此功能。

我已经在浏览器控制台中运行了这个函数,它可以工作。但是当我在DOMContentLoaded活动中运行它时,target总是null.

const mfn = function () {
  console.log('test');
  const url = window.location.href;
  const idIndex = url.indexOf('#');
  if (idIndex > -1) {
    const targetId = url.substr(idIndex + 1);
    console.log(targetId);
    const target = document.getElementById(targetId);
    console.log(target);  // null :(
    target.scrollIntoView();
  }
};
document.addEventListener("DOMContentLoaded", mfn);

有更好的事件可以使用吗?

更新: 我意识到这应该默认发生。出于某种原因,在我的 GatsbyJS 博客中,它没有发生。@Aaron Plocharczyk 的回答评论揭示了一个解决方案,但这很奇怪。将在 Gatbsy github 问题中提问。

标签: javascriptgatsby

解决方案


您不必编写额外的 JavaScript 来使页面跳转到具有 URL 中 ID 的元素。它应该已经将其作为默认行为,如下所示:https ://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#Examples 。您所指的这个元素是否有可能稍后通过 JavaScript DOM 操作动态填充到该页面?如果是这样,您需要在将元素添加到页面mfn 后调用。如果您找不到它添加到页面的位置,请尝试:

const url = window.location.href;
const idIndex = url.indexOf('#');
if(idIndex > -1){
    const targetId = url.substr(idIndex + 1);
    var elementLoadedCheck = setInterval(function(){
        if(document.getElementById(targetId)){
            const target = document.getElementById(targetId);
            console.log(target);
            target.scrollIntoView();
            clearInterval(elementLoadedCheck);
        }
    }, 100);
}

您也可能输入了错误的 ID。


推荐阅读