如何判断图片即将进入可视区域

方案1:clientHeight+scrollTop>offsetTop
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>判断图片即将进入可视区域</title>
</head>

<body>
    <div style="background-color: #36d;width:100vw;height:8000px">
    </div>
    <div id="yellow" style="background-color: yellow;width:100vw;height:800px">
    </div>

    <script>
        document.addEventListener('scroll', () => {
            const clientH = document.documentElement.clientHeight//获取屏幕可视区域的高度
            const scrollT = document.documentElement.scrollTop//获取浏览器窗口顶部与文档顶部之间的距离,也就是滚动条滚动的距离
            const offsetTop = document.getElementById('yellow').offsetTop//获取元素相对于文档顶部的高度
            if (clientH + scrollT > offsetTop) {
                console.log('进入可视区域啦')
            }
        })
    </script>
</body>

</html>
方案2:下滑过程中bound.top会越来越小
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>判断图片即将进入可视区域</title>
</head>

<body>
    <div style="background-color: #36d;width:100vw;height:8000px">
    </div>
    <div id="yellow" style="background-color: yellow;width:100vw;height:800px">
    </div>

    <script>
        document.addEventListener('scroll', () => {
            var bound = document.getElementById('yellow').getBoundingClientRect(); 获取元素的大小及位置,用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置
            var clientHeight = window.innerHeight; //innerHeight表示窗口内容区域的高度,这是不包括边框、菜单栏的
            if (bound.top <= clientHeight) {
                console.log('进入可视区域啦')
            }
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/m0_65489440/article/details/128950826
今日推荐