需求:
消息中心需要跳转到指定文章,指定评论页, 找到指定的评论, 然后滚动到那个地方
思路:
方法一:使用锚点路由(在路由上结尾加上#id,网页目标位置元素绑定id)
缺点:
- 会在url上加上#锚点
- 页面刷新失效
- vue 路由为锚点模式时会造成冲突
实现:
async mounted() {
console.log("sourceId", this.sourceId);
if (this.skipPage) {//目标页码
this.pageIndex = this.skipPage;
}
await this.getCommentList();
// window.location.hash = "#" + this.sourceId;
const { origin, pathname, search } = window.location;
window.location.href = origin + pathname + search + "#" + this.sourceId;
},
方式二:
使用浏览器DOM实现页面滚动到指定位置
优点:
- 不会照成url污染
- 简单快捷
实现:
this.$nextTick(() => {
if (this.sourceId) {
document.getElementById(this.sourceId).scrollIntoView();
}
});
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型参数
element.scrollIntoView(scrollIntoViewOptions); // Object型参数
alignToTop
可选
一个Boolean
值:
- 如果为
true
,元素的顶端将和其所在滚动区的可视区域的顶端对齐。相应的scrollIntoViewOptions: {block: "start", inline: "nearest"}
。这是这个参数的默认值。 - 如果为
false
,元素的底端将和其所在滚动区的可视区域的底端对齐。相应的scrollIntoViewOptions: {block: "end", inline: "nearest"}
。
scrollIntoViewOptions
可选
一个包含下列属性的对象:
-
behavior
可选定义动画过渡效果,
"auto"
或"smooth"
之一。默认为"auto"
。 -
block
可选定义垂直方向的对齐,
"start"
,"center"
,"end"
, 或"nearest"
之一。默认为"start"
。 -
inline
可选定义水平方向的对齐,
"start"
,"center"
,"end"
, 或"nearest"
之一。默认为"nearest"
。
资料:scrollIntoView
scrollIntoView兼容性好
用法简单
需要滚动到的元素.scrollIntoView()