javascript - 在视口中激活动画
问题描述
我正在尝试使用动画使图像从零不透明度过渡到完全不透明度。我使用的关键帧动画代码有效,但我想延迟开始直到图像出现。我试过几个 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;
}
解决方案
您可以使用 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 标签时,它都会添加淡入淡出类并淡入。
推荐阅读
- dialogflow-es - Dialogflow 中的后续意图未触发。怎么了?
- java - 我不明白我的程序的输出,请解释一下
- scala - 创建并行执行的列表组合器
- mips - 如何更改 MIPS 中的间接寻址?
- c - 位域的可用性
- javascript - 如何使用 Javascript 和 Firebase 从数据库中删除 child_object
- kubernetes - 是否有任何 pod 消耗了资源限制中指定的所有资源?
- java - 在不执行 map 或 flatMap 的情况下退出循环
- python - 处理多个 xml 文件并将所有输出保存在单个 .txt 文件中
- python - /login/ 'bool' 对象的 TypeError 不可调用