簡(jiǎn)單代碼實(shí)現(xiàn)H5下拉刷新和觸底加載更多

首先說(shuō)一下實(shí)現(xiàn)原理:
下拉刷新
實(shí)現(xiàn)下拉刷新主要分為三步:
監(jiān)聽(tīng)原生touchstart事件,記錄其初始位置的值,e.touches[0].pageY;
監(jiān)聽(tīng)原生touchmove事件,記錄并計(jì)算當(dāng)前滑動(dòng)的位置值與初始位置值的差值,大于0表示向下拉動(dòng),并借助CSS3的translateY屬性使元素跟隨手勢(shì)向下滑動(dòng)對(duì)應(yīng)的差值,同時(shí)也應(yīng)設(shè)置一個(gè)允許滑動(dòng)的最大值;
監(jiān)聽(tīng)原生touchend事件,若此時(shí)元素滑動(dòng)達(dá)到最大值,則觸發(fā)對(duì)應(yīng)的callback,同時(shí)將translateY重設(shè)為0,元素回到初始位置。
觸底加載更多
當(dāng)網(wǎng)頁(yè)向上卷曲出去的高度+瀏覽器高度=網(wǎng)頁(yè)正文高度的時(shí)候,判定為網(wǎng)頁(yè)已經(jīng)觸底。

下面直接上代碼
CSS代碼

#refreshContainer li {
    background-color: #eee;
    margin-bottom: 1px;
    padding: 20px 10px;
}
.refreshText {
    position: absolute;
    width: 100%;
    line-height: 50px;
    text-align: center;
    left: 0;
    top: 0;
}

HTML代碼

<p class="refreshText"></p>
<ul id="refreshContainer">
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
</ul>

JS代碼

(function (window, document, undefined) {
    var upDownRefresh = function (box, text) {
        var _element = document.getElementById(box),
            _refreshText = document.querySelector(text),
            _startPos = 0,
            _transitionHeight = 0;
        _element.addEventListener('touchstart', function (e) {
            console.log('初始位置:', e.touches[0].pageY);
            _startPos = e.touches[0].pageY;
            _element.style.position = 'relative';
            _element.style.transition = 'transform 0s';
        }, false);
        _element.addEventListener('touchmove', function (e) {
            // console.log('當(dāng)前位置:', e.touches[0].pageY);
            _transitionHeight = e.touches[0].pageY - _startPos;
            console.log(_transitionHeight)
            if (_transitionHeight > 0 && _transitionHeight < 60) {
                _refreshText.innerText = '下拉刷新';
                _element.style.transform = 'translateY(' + _transitionHeight + 'px)';
            }
        }, false);
        _element.addEventListener('touchend', function (e) {
            if (_transitionHeight > 55) {
                _refreshText.innerText = '更新中...';
                console.log("觸發(fā)更新")
            }
            _element.style.transition = 'transform 0.5s ease 1s';
            _element.style.transform = 'translateY(0px)';
        }, false);
    }
    window.upDownRefresh = upDownRefresh;
})(window, document);
new upDownRefresh("refreshContainer", ".refreshText")

如果我們要監(jiān)聽(tīng)的是整個(gè)頁(yè)面的觸底,則通過(guò)以下代碼就可以

window.onscroll = function () {
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    if (scrollTop + windowHeight == scrollHeight) {
        console.log('觸底加載更多')
    }
}

一定要完全觸底才觸發(fā)加載更多的事件會(huì)顯得不那么友好,我們可以設(shè)置一個(gè)距離范圍

window.onscroll = function () {
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    if (scrollTop + windowHeight + 40 >= scrollHeight) {
        console.log('觸底加載更多')
    }
}

但是這樣寫(xiě)有一個(gè)很大的缺點(diǎn)就是只要進(jìn)入到了這個(gè)距離范圍,觸底事件就會(huì)一直觸發(fā),即使此時(shí)頁(yè)面是向上滑動(dòng)的,只要還是在40這個(gè)距離范圍內(nèi)滑動(dòng),都會(huì)觸發(fā)觸底事件,這不是我們想要的,接下來(lái)對(duì)代碼進(jìn)行優(yōu)化:

let flag = ''
window.onscroll = function () {
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    if (flag === '' || flag === 'open') {
        if (scrollTop + windowHeight + 100 >= scrollHeight) {
            console.log('觸底加載更多')
            // 觸發(fā)了一次后閥門(mén)關(guān)閉
            flag = 'close'
        }
    }
    if (scrollTop + windowHeight + 100 < scrollHeight && (flag === '' || flag === 'close')) {
        console.log('開(kāi)啟閥門(mén)')
        flag = 'open'
    }
}

如果我們需要實(shí)現(xiàn)的是某個(gè)元素的觸底加載更多,則需要另外的實(shí)現(xiàn)方式:
樣式方面不多贅述,滾動(dòng)區(qū)域是給固定高度,設(shè)置 overflow-y: auto 來(lái)實(shí)現(xiàn)。
接下來(lái)看看js方面的實(shí)現(xiàn),其實(shí)也很簡(jiǎn)單,觸發(fā)的條件是:可視高度 + 滾動(dòng)距離 >= 實(shí)際高度 。例子我會(huì)使用vue來(lái)實(shí)現(xiàn),和原生實(shí)現(xiàn)是一樣的。

  • 可視高度(offsetHeight):通過(guò) dom 的 offsetHeight 獲得,表示區(qū)域固定的高度。這里我推薦通過(guò) getBoundingClientRect() 來(lái)獲取高度,因?yàn)槭褂们罢邥?huì)引起瀏覽器回流,造成一些性能問(wèn)題。
  • 滾動(dòng)高度(scrollTop):滾動(dòng)事件中通過(guò) e.target.scrollTop 獲取,表示滾動(dòng)條距離頂部的px
  • 實(shí)際高度(scrollHeight):通過(guò) dom 的 scrollHeight 獲得,表示區(qū)域內(nèi)所有內(nèi)容的高度(包括滾動(dòng)距離),也就是實(shí)際高度

基礎(chǔ)實(shí)現(xiàn)

onScroll(e) {
    let scrollTop = e.target.scrollTop
    let scrollHeight = e.target.scrollHeight
    let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
    let currentHeight = scrollTop + offsetHeight
    if (currentHeight >= scrollHeight) {
        console.log('觸底')
    }
}

加點(diǎn)細(xì)節(jié):
加點(diǎn)細(xì)節(jié),現(xiàn)在我們希望是離底部一定距離就觸發(fā)事件,而不是等到完全觸底。如果你做過(guò)小程序,這和onReachBottom差不多的意思。
聲明一個(gè)離底部的距離變量reachBottomDistance
這時(shí)候觸發(fā)條件:可視高度 + 滾動(dòng)距離 + reachBottomDistance >= 實(shí)際高度

export default {
  data(){
    return {
      reachBottomDistance: 100
    }
  },
  methods: {
    onScroll(e) {
        let scrollTop = e.target.scrollTop
        let scrollHeight = e.target.scrollHeight
        let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
        let currentHeight = scrollTop + offsetHeight + this.reachBottomDistance
        if (currentHeight >= scrollHeight) {
            console.log('觸底')
        }
    }
  }
}

在距離底部100px時(shí)成功觸發(fā)事件,但由于100px往下的區(qū)域是符合條件的,會(huì)導(dǎo)致一直觸發(fā),這不是我們想要的。
接下來(lái)做一些處理,讓其進(jìn)入后只觸發(fā)一次:

export default {
  data(){
    return {
      isReachBottom: false,
      reachBottomDistance: 100
    }
  },
  methods: {
    onScroll(e) {
        let scrollTop = e.target.scrollTop
        let scrollHeight = e.target.scrollHeight
        let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
        let currentHeight = scrollTop + offsetHeight + this.reachBottomDistance

        if(currentHeight < scrollHeight && this.isReachBottom){
          this.isReachBottom = false
        }
        if(this.isReachBottom){
          return
        }
        if (currentHeight >= scrollHeight) {
          this.isReachBottom = true
          console.log('觸底')
        }
    }
  }
}

優(yōu)化:
實(shí)時(shí)去獲取位置信息稍微會(huì)損耗性能,我們應(yīng)該把不變的緩存起來(lái),只實(shí)時(shí)獲取可變的部分

export default {
  data(){
    return {
      isReachBottom: false,
      reachBottomDistance: 100
      scrollHeight: 0,
      offsetHeight: 0,
    }
  },
  mounted(){
    // 頁(yè)面加載完成后  將高度存儲(chǔ)起來(lái)
    let dom = document.querySelector('.comment-area .comment-list')
    this.scrollHeight = dom.scrollHeight
    this.offsetHeight = Math.ceil(dom.getBoundingClientRect().height)
  },
  methods: {
    onScroll(e) {
        let scrollTop = e.target.scrollTop
        let currentHeight = scrollTop + this.offsetHeight + this.reachBottomDistance

        if(currentHeight < this.scrollHeight && this.isReachBottom){
          this.isReachBottom = false
        }
        if(this.isReachBottom){
          return
        }
        if (currentHeight >= this.scrollHeight) {
          this.isReachBottom = true
          console.log('觸底')
        }
    }
  }
}

上面代碼有個(gè)坑:scrollHeight會(huì)隨著每次觸底數(shù)據(jù)追加而變化,儲(chǔ)存起來(lái)影響后續(xù)的比對(duì)加載,接下來(lái)進(jìn)行改進(jìn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容