最近做项目需要从一个页面跳转至另一个页面的相应位置,于是需要锚点进行处理。尝试了很多方法,最后在这个作者文章中找到了解决答案,写的非常好
实现思路
- 从一个页面跳转至另一个页面时,不方便在路径中带参数,于是我放在localStorage中进行了一个参数的存储,之后在其余场景和页面销毁时做了localStorage的清除。
- 被跳转页面mounted时,会判断localStorage中跳转的参数是否存在,若存在,则跳转至对应位置
我的实现代码如下
跳转页面:
toUcBetaWithTime(cid: number) {
const toUrl = `${location.origin}/#/uc?cId=${cid}`
const flowUcObj = {
time_gte: this.formData.time_gte,
time_lte: this.formData.time_lte,
anchor_pos: 'platform_show'
}
localStorage.setItem('flowUcObj', JSON.stringify(flowUcObj))
// 存储时间信息至本地
window.open(toUrl, '_blank')
}
被跳转页面:
mounted() {
const flowUcObj = JSON.parse(<string>localStorage.getItem('flowUcObj')) || null
if (flowUcObj) {
this.anchor_pos = flowUcObj.anchor_pos
let target = document.querySelector(`#${this.anchor_pos}`)
target && target.scrollIntoView()
}
主要代码
- let target = document.querySelector(
#${this.anchor_pos}
) 获取锚点位置target - target && target.scrollIntoView() 滑动到对应位置
总结用法,希望可以帮助到你,
我是Ably,你无须超越谁,只要超越昨天的自己就好~