1. 程式人生 > 程式設計 >vue scroll滾動判斷的實現(是否滾動到底部、滾動方向、滾動節流、獲取滾動區域dom元素)

vue scroll滾動判斷的實現(是否滾動到底部、滾動方向、滾動節流、獲取滾動區域dom元素)

1、是否滾動到底部

 isScrollBottom() {
   // 是否滾動到了底部
   this.box = this.$refs.chatListWrapper
   var clientHeight = this.box.clientHeight
   var scrollTop = this.box.scrollTop
   var scrollHeight = this.box.scrollHeight
   if (scrollTop + clientHeight == scrollHeight) {
    this.$store.dispatch('setBottomBtn',false,{ root: true }) // 隱藏直達最新訊息按鈕
    this.isBottom = true
    this.isTop = false
   } else {
    this.$store.dispatch('setBottomBtn',true,{ root: true }) // 顯示直達最新訊息按鈕
    this.isTop = false
    this.isBottom = false
    if (scrollTop == 0) {
     this.isTop = true
    }
   }
  },

2、scroll滾動方向判斷

  getDirection() {
   // scroll滾動方向~~~~
   this.box = this.$refs.chatListWrapper
   var scrollTop = this.box.scrollTop
   var scroll = scrollTop - this.initTop
   this.initTop = scrollTop
   let dir = 'down'
   if (scroll < 0) {
    dir = 'up'
   } else {
    dir = 'down'
   }
   return dir
  },

3、滾動節流

1)、在滾動的dom上繫結scroll事件,監聽滾動

vue scroll滾動判斷的實現(是否滾動到底部、滾動方向、滾動節流、獲取滾動區域dom元素)

2)、data中定義:fnScroll: () => {}, 初始值
3)、mounted中給fnScroll函式賦值,_.throttle實現滾動節流

this.fnScroll = _.throttle(() => {
},500)

4、獲取滾動可視區域內dom:

實現注意:判斷當前元素是否在可視區域內,若在則存到isSeeDomArr中,然後迴圈isSeeDomArr陣列,拿到當前可視區域內的最後一個dom,再去判斷是否更新對應的諮詢軌跡。
不要滾動時就去更新,這樣會造成不停請求更新,最後一次請求可能無效,造成資料的錯亂

  sendRead() {
   const chatLi = document
    .getElementById('chat_list_wrapper')
    .getElementsByTagName('li')
   var container = this.$refs.chatListWrapper
   var swHeight = container.clientHeight
   const scrollTop = container.scrollTop
   const aa = swHeight + scrollTop
   let isSeeDomArr = []
   for (let j = 0; j < chatLi.length; j++) {
    if (scrollTop < chatLi[j].offsetTop && chatLi[j].offsetTop < aa) {
     isSeeDomArr.push(chatLi[j]) //將可視區域內所有dom儲存到isSeeDomArr
    }
   }
   if (isSeeDomArr.length) {
    // 非 ceo接診臺更新訊息的已讀狀態
    if (this.$route.path.indexOf('diagnose/ceo') === -1) {
     for (let m = 0; m < isSeeDomArr.length; m++) {
      const isSelfSend = isSeeDomArr[m].getAttribute('isSelfSend')
      const msgStatus = isSeeDomArr[m].getAttribute('msgStatus')
      const msgType = isSeeDomArr[m].getAttribute('msgType')
      if (!isSelfSend && !msgStatus && msgType !== 'notice') {
       const _id = isSeeDomArr[m].getAttribute('id')
       this.sendReadApi(_id)
      }
     }
    }
    // 更新聊天對應的諮詢軌跡
    this.setCurrentFdAsk(
     isSeeDomArr[isSeeDomArr.length - 1].getAttribute('fdAsk')
    )
   }
  },

the end:滾動載入這些判斷前前後後改了好多次,這次終於感覺邏輯比較清晰了,也算對自己有個交代。。。

到此這篇關於vue scroll滾動判斷的實現(是否滾動到底部、滾動方向、滾動節流、獲取滾動區域dom元素)的文章就介紹到這了,更多相關vue scroll滾動判斷內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!