检查ReactJs中的视口大小



我想检查viewport在调整大小时是否与html标签元素相交。为此,我在react js应用程序中创建了这个组件:

import React from "react";
import "./styles.css";
function isElementInViewport(el) {
var rect = el?.getBoundingClientRect() || {};
return rect.bottom >= 0 &&
rect.right >= 0 &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
}
export default function App() {
React.useEffect(()=> {
window.addEventListener('resize', (e) => {
const el = document.getElementById('test');
const a = isElementInViewport(el);
console.log(a)
});
},[])
return (
<div className="App">
<div id='test' style={{backgroundColor: 'red', height: '200px', width: '200px'}}>test</div>
</div>
);
}

演示:https://codesandbox.io/s/epic-goldwasser-ecotfg?file=/src/App.js: 479 - 480


从下到上调整视口的大小,我的函数没有给出false,即使它与红色元素相交。
问题:如何修复我的代码能够检查是否viewport相交的红色元素?

我认为您需要验证元素的两个边缘是否都没有触及用户的当前视图。这还需要包含用户的滚动位置。

查看https://codesandbox.io/s/gallant-lichterman-wxnfrf?file=/src/App.js,它检查红色框是否在视口内。

同样,你不需要为你想观察的元素添加ID,可以查看https://reactjs.org/docs/hooks-reference.html#useref了解更多关于在React中使用引用的信息。

最新更新