久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

如何利用JS檢查元素是否在視口內

瀏覽:97日期:2024-04-02 09:13:14
前言

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

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);});參考

how-to-check-an-element-is-in-viewport-4bcl

Intersection Observer API

總結

到此這篇關于如何利用JS檢查元素是否在視口內的文章就介紹到這了,更多相關JS檢查元素在視口內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 澄迈县| 会泽县| 云霄县| 垦利县| 正蓝旗| 三门县| 伊金霍洛旗| 大兴区| 广河县| 色达县| 星子县| 海原县| 南川市| 三都| 万载县| 邯郸市| 临朐县| 基隆市| 伊金霍洛旗| 郴州市| 淳化县| 九龙城区| 杭锦旗| 化德县| 涿州市| 临泽县| 娱乐| 丰原市| 仲巴县| 文昌市| 象山县| 锦州市| 奇台县| 萨迦县| 济源市| 江华| 岳阳市| 棋牌| 三亚市| 东乡族自治县| 呈贡县|