javascript - 直接访问 nuxt 应用程序中的 URL 时,初始页面加载时的滚动位置不会转到哈希/锚点位置
问题描述
我的 nuxt.js 应用程序中有一些锚链接。它工作正常。说,当我尝试通过具有 id 属性的 navbar/ 标签访问页面的一部分时,它工作正常。
<a href="#anchor">Scroll to anchor</a>
- 这有效
<nuxt-link to="#anchor">Scroll to anchor</a>
- 也有效
但是当我尝试通过 URL 直接访问相同的内容时 -xxx.com/test#anchor
它需要进入测试页面但不会滚动到#anchor div。
我尝试过的几种解决方法是,
<nuxt-link :to="{path: '/', hash: 'anchor'}">link</nuxt-link>
我也在 nuxt-config 中更改了支持此功能的滚动行为,
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash
}
} else {
return {
x: 0,
y: 0
}
}
},
这在负载上不起作用。我发现已经提出了同样的问题,但仍然存在,
解决方案
有一个类似的问题,这个黑客解决了它。
mounted() {
if (this.$route.hash) {
let hash = this.$route.hash
hash = hash.replace('#', '')
const anchor = document.getElementById(hash)
if (anchor) {
window.scrollTo({
top: anchor.getBoundingClientRect().top + window.scrollY,
})
}
}
},
推荐阅读
- typescript - 运行新类型定义的测试时出现“错误:未使用的文件”
- xml - XPath 何时不存在这样的元素?
- javascript - 如何让二进制图像在浏览器中呈现?
- python - 视频播放速度比预期的pyQt5和Opencv快
- php - php fopen:无法打开流:连接超时
- java - 如何检查当前用户是否在 Firebase (Android Java) 上通过身份验证
- google-sheets - 计算 Sigma 和
- mysql - mysql笛卡尔积调优性能
- java - 如何使用约束布局创建水平回收视图?
- c++ - 作用域枚举在传递给 MAKEWPARAM 时不会引发编译器错误。为什么?