解决scrollLeft、scrollTop为0

在这里插入图片描述
最近遇到从外面点之后弹框,显示当前是第几组,并且滚动到当前位置的需求
遇到的问题:第一次获取可以获取的scrollWidth,第二次打开弹框就是0,并且设置scrollLeft也不起作用

解决办法:
延时获取dom元素,【可以把document换成this.$el】
需要nextTick

在这之前我们可以先检查一下 是不是当前dom元素可以滚动,如果输出的值有变化 那么dom元素就没有问题

window.addEventListener('scroll', () => {
  let matchContent = this.$el.querySelector('.match-name-option')
  console.log(matchContent.scrollLeft)
}, true)
public lastName () {
    if (this.activeIndex-- === 0) {
      this.activeIndex = 0;
    }
    this.$emit('index-change', this.activeIndex);
    this.scrollLeft();
  }

  public nextName () {
    if (this.activeIndex++ === this.relationGroupOptions.length - 1) {
      this.activeIndex = this.relationGroupOptions.length - 1;
    }
    this.$emit('index-change', this.activeIndex);
    this.scrollLeft();
  }

  private scrollLeft () {
    this.$nextTick(() => {
    setTimeout(() => {
      const matchContent = this.$el.querySelector('.match-name-option');
      if (matchContent) {
        matchContent.scrollLeft = (matchContent.scrollWidth / this.relationGroupOptions.length * this.activeIndex);
      }
     }, 10)
    });
  }

补充
网页可见区域宽: document.body.clientWidth
网页可见区域高: document.body.clientHeight
网页可见区域宽: document.body.offsetWidth (包括边线的宽)
网页可见区域高: document.body.offsetHeight (包括边线的高)
网页正文全文宽: document.body.scrollWidth
网页正文全文高: document.body.scrollHeight
网页被卷去的高: document.body.scrollTop
网页被卷去的左: document.body.scrollLeft

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值