【问题标题】:Activate animation when in viewport在视口中激活动画
【发布时间】:2020-05-19 19:43:51
【问题描述】:

我正在尝试使用动画使图像从零不透明度过渡到完全不透明度。我使用的关键帧动画代码有效,但我想延迟开始直到图像出现。 试了好几个JS代码都没有用。

HTML

<div class="item2">
 <img src="images/winston-chen-qg8TGmBNdeY-unsplash.jpg" width="950" height="700" alt="wintson cheng unsplash" class="img">                     
</div>

CSS

@keyframes animate {
 from {opacity: 0;}
 to {opacity: 1;}
}

.img {
 width: 100vw;
 height: auto;
 animation-name: animate;
 animation-duration: 10s;
 animation-timing-function: ease-in;
}

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您可以使用 jQuery 轻松完成。

    CSS:

    img { opacity: 0; } /* this sets the opacity before it comes in so there isn't a jump */
    
    .img {
         width: 100vw;
         height: auto;
    }
    
    .fadein {
         animation: animate 10s forwards;
    }
    

    jQuery:

    https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js

    然后在脚本文件中:

        $(function() {
          $(window).scroll(function() {
            var $img = $(".img");
            $img.each(function() {
                var $y = $(document).scrollTop(),
                $wh = $(window).height(),
                $t = $(this).offset().top - $wh;
                if ($y > $t) {
                    $(this).addClass("fadein");
                }
            });
        });
    });
    

    每次看到 .img 标签时,它都会添加淡入淡出类并淡入。

    【讨论】:

    • 谢谢你,Thomas,感谢你的帮助。我已设法将所有图像的不透明度设置为 0,但淡入淡出动画不起作用。我应该对我的 HTML 进行调整吗?我需要保留任何关键帧代码吗?我尝试稍微调整 CSS 和 HTML 代码,但似乎没有任何效果。
    • 对不起,我添加了 .在 addClass 错误:我已经创建了一支笔给你看 - codepen.io/urbanedgedesign/pen/bGVQPpX
    • 此时代码会在类出现的那一刻添加类,因此动画会立即发生。您可以添加一个减号以稍微延迟它,使其在显示之前显示为 50px:$wh = $(window).height() - 50,
    猜你喜欢
    • 2013-09-26
    • 2020-10-31
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多