這篇文章給大家分享的是有關怎么利用JS檢查元素是否在視口內的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
分享兩個監測元素是否在視口內的方法
使用 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;
};判斷元素是否在視口內,如圖所示

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 要好。
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檢查元素是否在視口內”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。