js可视区域加载

       当元素处于可视区域时再加载,例如淘宝天猫上打开网页时不是所有图片都加载出来了,而是当滚动条滚动到那个区域时才加载出来图片。

方法:判断元素顶部到浏览器窗口顶部的距离是否小于可视区域高度,如果小于就显示。这里可以用一个方法: getBoundingClientRect(),该方法返回一个对象,该对象存储了元素四个边界到浏览器窗口上边和左边的距离。

代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>可视区域加载</title>
    <style>
        #showDiv {
            width: 500px;
            height: 350px;
            background-color: aqua;
            margin: 1000px auto 0 auto;
        }
        
        .showDiv {
            animation: loading 2s linear;
        }
        
        @keyframes loading {
            from {
                opacity: 0;
                transform: translate(-100%, 0);
            }
            to {
                opacity: 1;
                transform: translate(0, 0);
            }
        }
    </style>
</head>

<body>
    <div id="showDiv"></div>
    <script type="text/javascript">
        window.onscroll = function() {
            var show = document.getElementById("showDiv");
            // 获取浏览器窗口可视化高度
            var clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            // 获取showDiv元素顶部到浏览器窗口顶部的距离
            var showTop = show.getBoundingClientRect().top;
            // 如果距离小于可视化窗口高度,就给showDiv元素添加动画效果
            if (showTop <= clientH) {
                show.classList.add("showDiv");
            }
        };
    </script>
</body>

</html>

运行结果:

猜你喜欢

转载自blog.csdn.net/DreamFJ/article/details/81543078