网页移动到页面指定位置

需求:

​ 消息中心需要跳转到指定文章,指定评论页, 找到指定的评论, 然后滚动到那个地方

思路:

​ 方法一:使用锚点路由(在路由上结尾加上#id,网页目标位置元素绑定id)

​ 缺点:

  1. 会在url上加上#锚点
  2. 页面刷新失效
  3. 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实现页面滚动到指定位置

优点:
  1. 不会照成url污染
  2. 简单快捷
实现:
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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥呀呀呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值