溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么利用JS檢查元素是否在視口內

發布時間:2021-04-14 11:53:17 來源:億速云 閱讀:281 作者:小新 欄目:開發技術

這篇文章給大家分享的是有關怎么利用JS檢查元素是否在視口內的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

前言

分享兩個監測元素是否在視口內的方法

1. 位置計算

使用 Element.getBoundingClientRect() 方法返回元素相對于視口的位置

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
};

獲取瀏覽器窗口的寬高

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
  const vWidth = window.innerWidth || document.documentElement.clientWidth;
  const vHeight = window.innerHeight || document.documentElement.clientHeight;
};

判斷元素是否在視口內,如圖所示

怎么利用JS檢查元素是否在視口內

const isElementVisible = (el) => {
  const rect = el.getBoundingClientRect()
  const vWidth = window.innerWidth || document.documentElement.clientWidth
  const vHeight = window.innerHeight || document.documentElement.clientHeight

  
  if (
    rect.right < 0 ||
    rect.bottom < 0 ||
    rect.left > vWidth ||
    rect.top > vHeight
  ) {
    return false
  }

  return true
}

getBoundingClientRect 方法會使瀏覽器發生回流和重繪,性能消耗稍大,但兼容性比 Intersection Observer 要好。

2. Intersection Observer

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Intersection Observer API提供了一種異步檢測目標元素與祖先元素或 viewport 相交情況變化的方法。在目標元素與視口或者其他指定元素發生交集時和觸發配置的回調函數。

// 獲取要監測的元素
const boxes = document.querySelectorAll('.box')

// 創建觀察者,配置回調函數
// 通過 isIntersecting 屬性判斷元素與視口是否相交
const observer = new IntersectionObserver((entries, observer) => {
 entries.forEach((entry) => {
    console.log(
      entry.target,
      entry.isIntersecting ? "visible" : "invisible"
    );
  });
})

boxes.forEach((box) => {
  observer.observe(box);
});

感謝各位的閱讀!關于“怎么利用JS檢查元素是否在視口內”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

js
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女