vue滚动到指定位置

vue 滚动到指定位置

<div class="box1">
  <div v-for="i in 50" :key="'a' + i" :ref="'a' + i">{{ i }}</div>
</div>

⚠️ refs 当与v-for使用时,要加[0]

1.Element.scrollIntoView

MDN scrollIntoView

scroll(pos) {
  // 不受定位影响 ,但是水平及垂直方向无法自定义数值,只能 "start", "center", "end", 或 "nearest"之一
  //document.getElementById("idName").scrollIntoView();
  //或者
  // document.querySelector("#idName").scrollIntoView();
  this.$refs[pos][0].scrollIntoView({
    behavior: "smooth",
    block: "nearest",
    inline: "nearest"
  });
}

2.window.scrollTo

MDN scrollTo

scroll(pos) {
  
  window.scrollTo({
    //滚动到元素位置
    //top: this.$refs[pos][0].offsetTop,//offsetTop 相对于offsetparent 定位,当有定位时,不准确。
    top: this.$refs[pos][0].getBoundingClientRect().top + window.scrollY,//推荐使用。getBoundingClientRect 相对于当前视口的位置
    //top: 400//滚动到指定距离
    //top: 0,//滚动到顶部
    //top: document.documentElement.scrollHeight,//滚动到底部
    behavior: "smooth" // 平滑滚动
  });
}

Element.getBoundingClientRect()

HTMLElement.offsetTop

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值