js IntersectionObserver monitors the display and hiding of elements, and images are lazy loaded

IntersectionObserver monitors the display and hide, the ratio of the monitor element displayed in the visible window, 1: completely displayed, 0: completely blocked, the display and hide of the opacity and visibility controls will not be triggered. This api is often used for lazy loading of images.

Code:

<!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>

Guess you like

Origin blog.csdn.net/qq_42740797/article/details/123084955