国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

如何利用JS檢查元素是否在視口內(nèi)

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

分享兩個監(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),如圖所示

如何利用JS檢查元素是否在視口內(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

Intersection Observer API

總結(jié)

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

標簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 高雄县| 常州市| 贡嘎县| 集贤县| 陆川县| 松潘县| 安徽省| 磐安县| 剑河县| 思南县| 吉木萨尔县| 托克逊县| 西丰县| 棋牌| 姜堰市| 章丘市| 马龙县| 巴林左旗| 甘谷县| 新河县| 阳曲县| 克拉玛依市| 盈江县| 集贤县| 洪湖市| 常德市| 长海县| 江华| 湘潭市| 兰考县| 鄂托克旗| 大理市| 英德市| 平果县| 章丘市| 莒南县| 鹰潭市| 乐至县| 界首市| 彭州市| 桂阳县|