开发背景:Nuxt.js项目
一、页面间跳转定位
跳转前页面:
<nuxt-link to="/enterprise#企业开办">
<div class="pt-3 lg:pt-5 text-lg lg:text-xl">企业开办</div>
<div class="text-sm pt-1">查看更多</div>
</nuxt-link>
跳转后页面:
<div id="企业开办" class="container">
<div>企业开办内容</div>
</div>
mounted () {
if (location.hash) {
// 331 '#%E6%8B%9B%E5%95%86%E8%BD%BD%E4%BD%93'
console.log(331, location.hash)
const id = decodeURIComponent(location.hash)
console.log(id) // "#企业开办"
const el = document.querySelector(id)
if (!el) return
const rect = el.getBoundingClientRect()
const headerHeight = document.querySelector('.page-header').clientHeight
// 要两个nextTick才行
this.$nextTick(() => {
this.$nextTick(() => {
window.scroll(0, window.scrollY - headerHeight + rect.top)
})
})
}
}
注意: querySelector(param) 方法仅仅返回匹配指定选择器的第一个元素。
参数:指定一个或多个匹配元素的 CSS 选择器。 可以使用它们的 id, 类, 类型, 属性, 属性值等来选取元素。对于多个选择器,使用逗号隔开,返回第一个匹配的元素。
document.querySelector()方法详解:
document.querySelector()方法_huangbaokang的博客-优快云博客_document.queryselector
二、当前页面定位
// domId为需要定位的元素id
changeTab (domId) {
const el = document.getElementById(domId)
const rect = el.getBoundingClientRect()
// 固定页头的高度
const headerHeight = document.querySelector('.page-header').clientHeight
this.$nextTick(() => {
this.$nextTick(() => {
window.scroll(0, window.scrollY - headerHeight + rect.top)
})
})
}
记录于2022-3-2