滚动时动画开始

时间:2017-10-08 04:25:12

标签: javascript jquery html css

我有一个使用CSS3动画的条形图,当页面加载时动画当前会激活。

我遇到的问题是给定的条形图由于之前的大量内容而被放置在屏幕外,所以当用户向下滚动到它时,动画已经完成。

我正在寻找通过CSS3或jQuery的方法来仅在观看者看到图表时激活条形图上的CSS3动画。

.animation {
    width: 1000px;
    margin: 50px auto;
}

table {
    width: 100%;

}

.tr-box table,
.tr-box tr,
.tr-box td {
    border: 1px solid black;
    border-collapse: collapse;
}

.tr-box tr td:first-child {
    width: 20%;
    text-align: center;
}

.tr-box {
    margin-bottom: 20px;
}

.tr-box tr td {
    padding: 10px;
}




.a-box-animation {
    height: 40px;
    width: 100%;
    -webkit-animation-name: box;
    animation-name: box;
    -webkit-animation-duration: 6s;
    animation-duration: 6s;
    -webkit-animation-iteration-count: 1;
    animation-iteration-count: 1;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -webkit-animation-timing-function: ease-in-out;
    animation-timing-function: ease-in-out;
}


@keyframes box {
    0% {
        width: 0%;
        background-color: blue;

    }
    100% {
        background-color: blue
    }
}
<section id="popularity">

        <div class="animation ">

            <h2>Most popular books</h2>
            <div class='tr-box'>
                <table>
                    <tr>
                        <td>The Snowman</td>
                        <td>
                            <div class="a-box-animation">

                            </div>
                        </td>
                    </tr>
                </table>
            </div>
          </div>

    </section>

=======

2 个答案:

答案 0 :(得分:0)

您可以向scroll事件添加事件处理程序,并在滚动时检查元素是否在视口中。如果是,则为其添加一个额外的类以启用其动画。

function isElementInViewport (el) {

    //special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

$(window).scroll(function() {
    if (isElementInViewport($('.box'))) {
        $('.box').addClass('animate')
    }
})

您需要将常规css样式提取到类box之类的类中,并将有关动画的样式放入类animate

答案 1 :(得分:0)

我尝试使用滚动事件。当元素进入当前视点时 - 脚本为元素添加一个类

addEventListener('scroll', function(){
  var current_pos = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
  if (current_pos - $('#popularity').offset().top < $(window).height() * 0.2) {
    $('#animation-box').addClass('a-box-animation');
  }
});

我删除带动画的类并为其添加id

<div id="animation-box"></div>