如何在视图/滚动上触发CSS动画?



我有这个简单的动画线形图代码。动画效果很好,但它是从页面加载开始的。我想让它在该部分出现在查看器的屏幕上/当查看器滚动到页面的该部分时开始。

如果它需要其他代码,如JS。请告诉我。谢谢你!

这里是HTML和CSS代码。这是一个Codepen的演示

HTML:

<div class="wrapper">
<h3>Papua New Guinea</h3>
<br>
<p>Papua New Guinea is one of the most culturally diverse countries in the world.
As of 2019, it is also the most rural, as only 13.25% of its people live in urban centres.
Most of the
population of more than 8,000,000 people live in customary communities, which are as diverse
as the languages.</p>
<h5>Living in Urban communities</h5>
<div class="line line1">13.25%</div>
<h5>Living in Customary Communities</h5>
<div class="line line2">86.75</div>
</div>

CSS:

.wrapper {
width: 800px;
margin: 0 auto;
}
.wrapper h3 {
text-align: center;
text-transform: uppercase;
margin-top: 40px;
}
.wrapper h5 {
text-align: left;
}
.line {
height: 25px;
min-width: 800px;
margin: 0 auto 10px;
line-height: 25px;
font-size: 14px;
color: #fff;
padding: 0 0 0 10px;
position: relative;
}
.line:before {
content: "";
width: 100%;
position: absolute;
left: 0;
height: 25px;
top: 0;
z-index: -2;
background: #d2d6d7;
}
.line:after {
content: "";
background: #333;
height: 25px;
transition: 0, 8s;
display: block;
width: 100%;
animation: animate 1 4s;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
.line1:after {
max-width: 13.25%;
}
.line2:after {
max-width: 86.75%;
}
@keyframes animate {
0% {
width: 0;
}
100% {
width: 100%;
}
}

您可以使用animation-delay,但这对您没有帮助。您可以使用JS代码来跟踪事件。代码如下:

var $win = $(window);
var $marker = $('#marker');
$win.scroll(function() {
if ($win.scrollTop() + $win.height() >= $marker.offset().top) {
$win.unbind('scroll');
// load there
}
});