天天看點

JavaScript中如何判斷一個元素是否在可視區域?

一、用途

可視區域即我們浏覽網頁的裝置肉眼可見的區域,如下圖

JavaScript中如何判斷一個元素是否在可視區域?

在日常開發中,我們經常需要判斷目标元素是否在視窗之内或者和視窗的距離小于一個值(例如 100 px),進而實作一些常用的功能,例如:

  • 圖檔的懶加載
  • 清單的無限滾動
  • 計算廣告元素的曝光情況
  • 可點選連結的預加載

二、實作方式

判斷一個元素是否在可視區域,我們常用的有三種辦法:

  • offsetTop、scrollTop
  • getBoundingClientRect
  • Intersection Observer

offsetTop、scrollTop

offsetTop,元素的上外邊框至包含元素的上内邊框之間的像素距離,其他offset屬性如下圖所示:

JavaScript中如何判斷一個元素是否在可視區域?

下面再來了解下clientWidth、clientHeight:

  • clientWidth:元素内容區寬度加上左右内邊距寬度,即clientWidth = content + padding
  • clientHeight:元素内容區高度加上上下内邊距高度,即clientHeight = content + padding

這裡可以看到client元素都不包括外邊距

最後,關于scroll系列的屬性如下:

  • scrollWidth 和 scrollHeight 主要用于确定元素内容的實際大小
  • scrollLeft 和 scrollTop 屬性既可以确定元素目前滾動的狀态,也可以設定元素的滾動位置
  • 垂直滾動 scrollTop > 0水準滾動 scrollLeft > 0
  • 将元素的 scrollLeft 和 scrollTop 設定為 0,可以重置元素的滾動位置

注意

  • 上述屬性都是隻讀的,每次通路都要重新開始

下面再看看如何實作判斷:

公式如下:

el.offsetTop - document.documentElement.scrollTop <= viewPortHeight           

代碼實作:

function isInViewPortOfOne (el) {
    // viewPortHeight 相容所有浏覽器寫法
    const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight 
    const offsetTop = el.offsetTop
    const scrollTop = document.documentElement.scrollTop
    const top = offsetTop - scrollTop
    return top <= viewPortHeight
}           

getBoundingClientRect

傳回值是一個 DOMRect對象,擁有left, top, right, bottom, x, y, width, 和 height屬性。

const target = document.querySelector('.target');
const clientRect = target.getBoundingClientRect();
console.log(clientRect);           

屬性對應的關系圖如下所示:

JavaScript中如何判斷一個元素是否在可視區域?

當頁面發生滾動的時候,top與left屬性值都會随之改變

如果一個元素在視窗之内的話,那麼它一定滿足下面四個條件:

  • top 大于等于 0
  • left 大于等于 0
  • bottom 小于等于視窗高度
  • right 小于等于視窗寬度

實作代碼如下:

function isInViewPort(element) {
  const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  const {
    top,
    right,
    bottom,
    left,
  } = element.getBoundingClientRect();

  return (
    top >= 0 &&
    left >= 0 &&
    right <= viewWidth &&
    bottom <= viewHeight
  );
}           

Intersection Observer

Intersection Observer 即重疊觀察者,從這個命名就可以看出它用于判斷兩個元素是否重疊,因為不用進行事件的監聽,性能方面相比getBoundingClientRect 會好很多

使用步驟主要分為兩步:建立觀察者和傳入被觀察者

建立觀察者

const options = {
  // 表示重疊面積占被觀察者的比例,從 0 - 1 取值,
  // 1 表示完全被包含
  threshold: 1.0, 
  root:document.querySelector('#scrollArea') // 必須是目标元素的父級元素
};

const callback = (entries, observer) => { ....}

const observer = new IntersectionObserver(callback, options);           

通過new IntersectionObserver建立了觀察者 observer,傳入的參數 callback 在重疊比例超過 threshold 時會被執行`

關于callback回調函數常用屬性如下:

// 上段代碼中被省略的 callback
const callback = function(entries, observer) { 
    entries.forEach(entry => {
        entry.time;               // 觸發的時間
        entry.rootBounds;         // 根元素的位置矩形,這種情況下為視窗位置
        entry.boundingClientRect; // 被觀察者的位置舉行
        entry.intersectionRect;   // 重疊區域的位置矩形
        entry.intersectionRatio;  // 重疊區域占被觀察者面積的比例(被觀察者不是矩形時也按照矩形計算)
        entry.target;             // 被觀察者
    });
};           

傳入被觀察者

通過 observer.observe(target) 這一行代碼即可簡單的注冊被觀察者

const target = document.querySelector('.target');
observer.observe(target);           

三、案例分析

實作:建立了一個十萬個節點的長清單,當節點滾入到視窗中時,背景就會從紅色變為黃色

Html結構如下:

<div class="container"></div>           

css樣式如下:

.container {
    display: flex;
    flex-wrap: wrap;
}
.target {
    margin: 5px;
    width: 20px;
    height: 20px;
    background: red;
}           

往container插入1000個元素

const $container = $(".container");

// 插入 100000 個 <div class="target"></div>
function createTargets() {
  const htmlString = new Array(100000)
    .fill('<div class="target"></div>')
    .join("");
  $container.html(htmlString);
}           

這裡,首先使用getBoundingClientRect 方法進行判斷元素是否在可視區域

function isInViewPort(element) {
    const viewWidth = window.innerWidth || document.documentElement.clientWidth;
    const viewHeight =
          window.innerHeight || document.documentElement.clientHeight;
    const { top, right, bottom, left } = element.getBoundingClientRect();

    return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
}           

然後開始監聽scroll事件,判斷頁面上哪些元素在可視區域中,如果在可視區域中則将背景顔色設定為yellow

$(window).on("scroll", () => {
    console.log("scroll !");
    $targets.each((index, element) => {
        if (isInViewPort(element)) {
            $(element).css("background-color", "yellow");
        }
    });
});           

通過上述方式,可以看到可視區域顔色會變成黃色了,但是可以明顯看到有卡頓的現象,原因在于我們綁定了scroll事件,scroll事件伴随了大量的計算,會造成資源方面的浪費

下面通過Intersection Observer的形式同樣實作相同的功能

首先建立一個觀察者

const observer = new IntersectionObserver(getYellow, { threshold: 1.0 });           

getYellow回調函數實作對背景顔色改變,如下:

function getYellow(entries, observer) {
    entries.forEach(entry => {
        $(entry.target).css("background-color", "yellow");
    });
}           

最後傳入觀察者,即.target元素

$targets.each((index, element) => {
    observer.observe(element);
});           

可以看到功能同樣完成,并且頁面不會出現卡頓的情況.

#頭條創作挑戰賽#

繼續閱讀