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)
}

 

就是這樣啦

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章