如何利用JS檢查元素是否在視口內(nèi)
前言
分享兩個監(jiān)測元素是否在視口內(nèi)的方法
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; };
判斷元素是否在視口內(nèi),如圖所示
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 方法會使瀏覽器發(fā)生回流和重繪,性能消耗稍大,但兼容性比 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 相交情況變化的方法。在目標元素與視口或者其他指定元素發(fā)生交集時和觸發(fā)配置的回調(diào)函數(shù)。
// 獲取要監(jiān)測的元素 const boxes = document.querySelectorAll('.box') // 創(chuàng)建觀察者,配置回調(diào)函數(shù) // 通過 isIntersecting 屬性判斷元素與視口是否相交 const observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { console.log( entry.target, entry.isIntersecting ? "visible" : "invisible" ); }); }) boxes.forEach((box) => { observer.observe(box); });
參考
how-to-check-an-element-is-in-viewport-4bcl
總結(jié)
到此這篇關(guān)于如何利用JS檢查元素是否在視口內(nèi)的文章就介紹到這了,更多相關(guān)JS檢查元素在視口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript數(shù)據(jù)推送Comet技術(shù)詳解
這篇文章主要為大家詳細介紹了JavaScript數(shù)據(jù)推送Comet技術(shù),感興趣的小伙伴們可以參考一下2016-04-04利用JavaScript做數(shù)獨的完整實現(xiàn)過程
數(shù)獨游戲是在一個9*9的方格中進行填數(shù)字的游戲,需要滿足的規(guī)則是每行每列和每個子九宮格都是1~9的不重復(fù)數(shù)字,下面這篇文章主要給大家介紹了關(guān)于如何利用JavaScript做數(shù)獨的相關(guān)資料,需要的朋友可以參考下2021-09-09