如何利用JS檢查元素是否在視口內(nèi)
分享兩個(gè)監(jiān)測(cè)元素是否在視口內(nèi)的方法
1. 位置計(jì)算使用 Element.getBoundingClientRect() 方法返回元素相對(duì)于視口的位置
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 方法會(huì)使瀏覽器發(fā)生回流和重繪,性能消耗稍大,但兼容性比 Intersection Observer 要好。
2. Intersection ObserverThe 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提供了一種異步檢測(cè)目標(biāo)元素與祖先元素或 viewport 相交情況變化的方法。在目標(biāo)元素與視口或者其他指定元素發(fā)生交集時(shí)和觸發(fā)配置的回調(diào)函數(shù)。
// 獲取要監(jiān)測(cè)的元素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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. django queryset相加和篩選教程2. idea設(shè)置提示不區(qū)分大小寫的方法3. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算4. IDEA 2020.1.2 安裝教程附破解教程詳解5. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟6. Java實(shí)現(xiàn)的迷宮游戲7. Java PreparedStatement用法詳解8. Spring如何集成ibatis項(xiàng)目并實(shí)現(xiàn)dao層基類封裝9. Java利用TCP協(xié)議實(shí)現(xiàn)客戶端與服務(wù)器通信(附通信源碼)10. JS圖片懶加載庫(kù)VueLazyLoad詳解

網(wǎng)公網(wǎng)安備