vue+ts+装饰器 @Ref 获取元素距离顶部的位置

    <div>
      <el-button type="primary" ref="ceshi" @click="goSome">点击</el-button>
    </div>
 
  @Ref() readonly ceshi
  mounted() {
   this.$nextTick(() => {
    console.log(this.ceshi.$el.offsetTop)
    console.log(this.ceshi.$el.getBoundingClientRect().top)
   })
  }

 // 这个是滚动的调用
 goSome() {
    utils.scrollToAppoint(this.ceshi.$el.offsetTop - 60)
  }



// 这种在写的时候 不去主动确定其类型(毕竟好多其实也不清楚是什么类型的)
@Ref() readonly ceshi

// 如果我们确定其类型,也能写的具体些, 但是在使用属性的时候 容易报警~
@Ref('ceshi') readonly ss!: HTMLButtonElement


// 目测HTMLButtonElement应该是 this.ceshi.$el.__proto__的名称

关于@Ref

 

下面的是通过vue的ref获取元素距离顶部的属性,用来做滚动的~

很明显 他们两个的计算方式是不同的~

Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。

MDN的说明 很详细了 此api计算的是相对于视口左上角的值

而offsetTop则是计算的距离其父元素顶部的高度~

需要注意的是 在vue中获取和dom相关的属性的时候 最好加上$nextTick, 毕竟不能确定什么时候渲染完毕

 

下面说下滚动~

 // 调用
 goSome() {
    utils.scrollToAppoint(this.ceshi.$el.offsetTop - 60)
  }


// 在utils中定义的滚动方法
utils.scrollToAppoint = ( to: number, from: number, el: any, duration: number = 500) => {
  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = window.webkitRequestAnimationFrame
      || function (callback: any): any {
        return window.setTimeout(callback, 1000 / 60)
      }
  }
  
  // 默认滚动的容器为#content  views/home
  el = !el ? document.querySelector('#content') : el
  // 默认为content的滚动条的位置
  from = !from ? el.scrollTop : from

  const difference = Math.abs(from - to);
  const step = Math.ceil((difference / duration) * 50)

  function scroll(start: any, end: any, step: any) {
    if (start === end) return false

    let d = start + step > end ? end : start + step
    if (start > end) { d = start - step < end ? end : start - step }

    if (el === window) {
      window.scrollTo(d, d)
    } else {
      el.scrollTop = d
    }
    window.requestAnimationFrame(() => scroll(d, end, step))
  }
  scroll(from, to, step)
}

 

就是这样啦

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值