使用jQuery或者原生JavaScript實(shí)現(xiàn)判斷元素是否在可視區(qū)

一、jQuery

function isVisible($node) {
    var windowH = $(window).height(),// 窗口高度  視口高度
        scrollH = $(window).scrollTop(), // 滾動(dòng)條高度
        $nodeOffsetH = $node.offset().top, // 元素距離文檔頂部的高度
        $nodeHeight = $node.outerHeight(); // 元素自身高度 沒用true 因此不包含margin

    // console.log($(document).height() ,'$(document).height() ')

    // 如果滾動(dòng)高度大于 元素距離文檔頂部的高度加上元素的自身高度( 說明 元素滾過頭了)
    // 或者  元素距離文檔頂部的高度 大于 滾動(dòng)高度加上窗口高度 (說明  還沒滾到)
    // 這兩個(gè)條件只要滿足其一  就不在可視區(qū)

    if (!(scrollH > ($nodeOffsetH + $nodeHeight - 5) || (scrollH + windowH) < $nodeOffsetH)) {
        // 這里減5 為修正值 點(diǎn)擊a 標(biāo)簽錨點(diǎn)定位時(shí) 有2px左右的誤差
        return true
    } else {
        return false
    }

}

二、原生JavaScript

 function  isVisible(node) {
      const windowH = window.innerHeight;// 窗口高度  視口高度
      const scrollH = document.querySelector('.main-content').scrollTop; // 滾動(dòng)條高度
      const nodeOffsetH = node.offsetTop; // 元素距離文檔頂部的高度
      const nodeHeight = node.offsetHeight; // 元素自身高度  不包含margin
      // console.warn(windowH, scrollH, nodeOffsetH, nodeHeight, 'windowH,scrollH,nodeOffsetH,nodeHeight')

      // console.log($(document).height() ,'$(document).height() ')

      // 如果滾動(dòng)高度大于 元素距離文檔頂部的高度加上元素的自身高度( 說明 元素滾過頭了)
      // 或者  元素距離文檔頂部的高度 大于 滾動(dòng)高度加上窗口高度 (說明  還沒滾到)
      // 這兩個(gè)條件只要滿足其一  就不在可視區(qū)

      if (!(scrollH > ((nodeOffsetH + nodeHeight) - 5) || (scrollH + windowH) < nodeOffsetH)) {
        // 這里減5 為修正值 點(diǎn)擊a 標(biāo)簽錨點(diǎn)定位時(shí) 有2px左右的誤差
        return true
      }
      return false
    }
?著作權(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)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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