html
<style>
* {
padding: 0;
margin: 0;
}
header,
main,
footer {
display: flex;
justify-content: center;
align-items: center;
}
.container,
.footer {
height: 1000px;
width: 100%;
}
.main {
height: 300px;
width: 100%;
}
</style>
</head>
<body>
<header class="container">
<span>header</span>
</header>
<main class="main">
<span>content</span>
</main>
<footer class="footer">
<span>footer</span>
</footer>
</body>
方法1
function isInViewport(element) {
// 使用getBoundingClientRect()方法:这个方法返回一个DOM元素的位置信息,包括元素的顶部、底部、左侧和右侧相对于视口的坐标。通过比较元素的位置信息和视口的大小,可以判断元素是否在可视区内。
const rect = element.getBoundingClientRect();
const windowHeight =
window.innerHeight || document.documentElement.clientHeight;
const windowWidth = window.innerWidth || document.documentElement.clientWidth;
// 判断元素上下左右边界是否都在可视区内
const isInsideViewport =
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= windowHeight &&
rect.right <= windowWidth;
return isInsideViewport;
}
// 使用示例:
// console.log(isInViewport(element)); // 返回true或false
const element = document.querySelector('.main')
document.addEventListener('scroll', function() {
// console.log(123);
console.log(isInViewport(element)); // 返回true或false
})
方法2
// 使用Intersection Observer API:这是现代浏览器提供的一个API,用于监测目标元素与其祖先元素或视口的交叉状态。
// 通过创建一个IntersectionObserver实例,并设置回调函数,可以判断元素是否进入或离开可视区。
const options = {
root: null,
rootMargin: '0px',
threshold: 0.5
};
function callback(entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
console.log(entry.target.id + ' 进入可视区');
} else {
console.log(entry.target.id + ' 离开可视区');
}
});
}
const observer = new IntersectionObserver(callback, options);
// 使用示例:
const element = document.querySelector('.main');
// observer.observe(element);
// wheel 滚轮时间
document.addEventListener('wheel', function() {
observer.observe(element);
})