获取一个元素的显示次数可以通过IntersectionObserver实现
html代码
<div class="tips">box is visible</div>
<div class="box">box</div>
js代码
<script>
const $tips = document.querySelector('.tips')
const callback = (entries) => {
entries.forEach((entry) => {
console.log(entry.intersectionRatio)
if (entry.intersectionRatio > 0) {
$tips.innerHTML = 'box is visible'
} else if (entry.intersectionRatio <= 0) {
$tips.innerHTML = 'box is hidden'
}
});
}
const options = {
// A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.
// threshold: 1,
}
const observer = new IntersectionObserver(callback, options)
observer.observe(document.querySelector('.box'))
</script>```