滚动到页面的特定部分后启动CSS动画

时间:2018-03-12 05:24:37

标签: javascript jquery html css

我正在尝试使用网页上的CSS动画图像。动画工作正常,但我想只在用户到达页面的特定部分时才开始动画。这是我的代码:

<div class="sec1-right">
   <img class="sec1-dmush1" src ="sec1-dmush1.png">
</div>

CSS

.sec1-right{
    position: relative;
    width: 50%;
    float: right;
    box-sizing: border-box;
    min-height: 600px;
    margin-top: 86px;
}

/* first section animation */
.sec1-dmush1 {
    animation: fadeAndScale .9s cubic-bezier(.45,-0.22,.34,1.69);
    transform-origin:center bottom;
    max-width: 150px;
    width: 100%;
    position: absolute;
    left: 180px;
    top: 300px;
    z-index: 0;
}

动画

@keyframes fadeAndScale{
    from{
        opacity:0;
        transform: scale3d(0,0,1);
    }
    to{
        opacity: 1;
        transform: scale3d(1,1,1);
    }
}

我如何实现

2 个答案:

答案 0 :(得分:0)

您需要在javascript中编写DLP API has not been used in project ****** before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/dlp.googleapis.com/overview?project=******** then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.个事件。元素scroll减去offsetTop高度。所以只要元素进入视口事件开始。

Javascript:

window

JsFiddle

jQuery:

var scrollpos = window.scrollY; // window scroll position
var wh = window.innerHeight-50; // as soon as element touches bottom with offset event starts
var element = document.querySelector(".sec1-dmush1"); //element

window.addEventListener('scroll', function(){ 
    if(scrollpos > (element.offsetTop - wh)){
        element.classList.add("onScroll");
    }
});

jsFiddle

如果您有多个动画元素。您可以使用 waypoint js 来减少一些努力。

$(window).scroll(function(){
  var wh = $(window).height()-50;
    if($(window).scrollTop() > $('.sec1-dmush1').offset().top-wh){
    $('.sec1-dmush1').addClass('onScroll');
  }
});

jsFiddle

答案 1 :(得分:-2)

使用javascript你可以找到滚动事件。具体的px(高度)之后。您可以将类添加到您尝试设置动画的现有类(jquery)。