1. 程式人生 > >【Web前端】瀏覽器拖動到底部執行相關程式碼

【Web前端】瀏覽器拖動到底部執行相關程式碼

利用 jQuery 實現

滑動到最底部實現相關功能,例如載入。

//獲取某個 div 距離瀏覽器頂部的距離
var $top = $this.offset().top;
//獲取到整個文件的高度
var $heightOfDocument = $(document).height();
//獲取當前瀏覽器可視高度
var $heightOfWindow = $(window).height();

if ($heightOfDocument - $heightOfWindow === $top) {
    //執行程式碼

} else {
    return false;
}

滑到到距離底部一段距離就開始載入相關程式碼:

//獲取某個 div 距離瀏覽器頂部的距離
var $top = $this.offset().top;
//獲取到整個文件的高度
var $heightOfDocument = $(document).height();
//獲取當前瀏覽器可視高度
var $heightOfWindow = $(window).height();

//這裡給 $top 加上一個值,讓前面兩個的差小於這個值即可。
if ($heightOfDocument - $heightOfWindow <= $top + 100) { 
    //執行程式碼

} else {
    return false;
}

利用 javascript 實現

var scrollTop = getScrollTop();
var clientHeight = getClientHeight();
var offsetHeight = getOffsetHeight();
for (var i = 0; i < items.length; i++) {
    var offsetTop = items[i].offsetTop;
    if (offsetHeight - clientHeight <= scrollTop + 100) {
      //執行程式碼

    } else {
      break;
    }
 }

function getOffsetHeight() {
        return document.documentElement.offsetHeight || document.body.offsetHeight;
}

function getClientHeight() {
    return document.documentElement.clientHeight || document.body.clientHeight;
}