javascript - 尝试在新标签加载时滚动到目标 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 问题中提问。
解决方案
您不必编写额外的 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。
推荐阅读
- azure - Ansible - 标记 Azure 运行的虚拟机
- elasticsearch - 将地理边界框扩展 x 英里的计算
- java - Spring Security OAuth 2 资源服务器:为 jwt 验证转换 jwks 不支持 use==enc
- reactjs - Enzyme Shallow 不渲染组件,输出为
- python - 如何从 RPGLE 调用 Python 并返回一个值?
- reactjs - React Router:子组件中定义的路由不起作用
- javascript - 从 Mongoose 获取数据
- angular - 根据ngIf以相同的角度形式禁用提交按钮
- reactjs - 如何在 ExtJs 组件中加载 React 应用程序 / Lib
- javascript - TypeError - Router.use() 需要一个中间件函数但有一个未定义的