可视区域加载动画

作者:lMadman
链接:https://www.jianshu.com/p/c165f2e06a44
來源:简书

有一些需求,是当我们去浏览时才会去加载,譬如一些动画,和一些图片,那么这些是怎样实现的呢?
先来看一下下面的一段小代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>可视区域加载</title>
</head>
<style>
    #showDiv{
        width: 500px;
        height: 350px;
        background-color: red;
        margin: 1000px auto 0 auto;
    }
    @-webkit-keyframes fadeInLeft {
        0%{
            opacity: 0;
            -webkit-transform: translate3d(-100%,0,0);
            -moz-transform: translate3d(-100%,0,0);
            -ms-transform: translate3d(-100%,0,0);
            -o-transform: translate3d(-100%,0,0);
            transform: translate3d(-100%,0,0);
        }
        100%{
            opacity: 1;
            -webkit-transform: none;
            -moz-transform: none;
            -ms-transform: none;
            -o-transform: none;
            transform: none;
        }
    }
    .fadeInLeft{
        animation-name: fadeInLeft;
        -webkit-animation-name: fadeInLeft;
        animation-duration: 2s;
        -webkit-animation-duration: 2s;
    }
</style>
<body>
    <div id="showDiv"></div>
</body>
<script>
    function showDiv() {
        var showId = document.getElementById('showDiv');
        var clients = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var divTop = showId.getBoundingClientRect().top;
        if(divTop<=clients){
            showId.classList.add('fadeInLeft');
        }else{
            showId.classList.remove('fadeInLeft');
        }
    }
    window.onscroll = showDiv;
</script>
</html>

这里主要用到了CSS3中的动画以及getBoundingClientRect()获取div到浏览器顶部的距离,和浏览器的可视高度进行对比。
先来看下getBoundingClientRect()这个方法:
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CODING_1/article/details/84347002