[英]Activate animation when in viewport
I am trying to use animate to make images transition from zero opacity to full opacity.我正在尝试使用动画使图像从零不透明度过渡到完全不透明度。 The keyframes animation code i have used works but i want to delay the start until the image is in view.
我使用的关键帧 animation 代码有效,但我想延迟开始直到图像出现。 I have tried several JS codes which have not worked.
我试过几个 JS 代码都没有用。
HTML HTML
<div class="item2">
<img src="images/winston-chen-qg8TGmBNdeY-unsplash.jpg" width="950" height="700" alt="wintson cheng unsplash" class="img">
</div>
CSS 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;
}
You could do it easily with jQuery.您可以使用 jQuery 轻松完成。
CSS: 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: jQuery:
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
Then in scripts file:然后在脚本文件中:
$(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");
}
});
});
});
Every time the.img tag comes into view it adds the fadein class and fades in.每次看到 .img 标签时,它都会添加淡入 class 并淡入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.