我正在尝试编写一个读取 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 issues 中提问。
最佳答案
您不必编写额外的 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。
关于javascript - 尝试在新选项卡加载时滚动到目标 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525524/