js IntersectionObserver监听元素的显示与隐藏,图片懒加载

IntersectionObserver监听显隐,监听元素在可视窗口中展示的比例,1:完全展示出来了,0:完全遮挡了,opacity和visibility控制的显隐是不会触发的。该api常用于图片懒加载。

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width:100px;
            height:100px;
            margin: 10px;
            background: #ccc;
        }
    </style>
</head>
<body>
    <div class="box box1" style="margin-top:500px"></div>
    <div class="box box2" style="margin-top:500px"></div>
</body>
</html>
<script>
//监听元素显隐,首次会触发,opacity和visibility控制的显隐不会触发。
const intersectionObserver = new IntersectionObserver(function(entries){
    console.log('变化');
    entries.forEach(item => {
        console.log('节点:',item.target);
        console.log('当前显隐比例:',item.intersectionRatio);//1:完全显示,0:完全隐藏。
    })
},{
    threshold: [0.5, 1]
});

intersectionObserver.observe( document.querySelector('.box1'));
intersectionObserver.observe( document.querySelector('.box2'));
</script>

猜你喜欢

转载自blog.csdn.net/qq_42740797/article/details/123084955
今日推荐