我有一个使用 CSS3 制作动画的条形图,动画当前在页面加载时激活。
我遇到的问题是,由于前面有很多内容,给定的条形图被放置在屏幕外,所以当用户向下滚动到它时,动画已经完成。
我一直在寻找通过 CSS3 或 jQuery 仅在查看者看到图表时激活条形图上的 CSS3 动画的方法。
.animation {
width: 1000px;
margin: 50px auto;
}
table {
width: 100%;
}
.tr-box table,
.tr-box tr,
.tr-box td {
border: 1px solid black;
border-collapse: collapse;
}
.tr-box tr td:first-child {
width: 20%;
text-align: center;
}
.tr-box {
margin-bottom: 20px;
}
.tr-box tr td {
padding: 10px;
}
.a-box-animation {
height: 40px;
width: 100%;
-webkit-animation-name: box;
animation-name: box;
-webkit-animation-duration: 6s;
animation-duration: 6s;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
@keyframes box {
0% {
width: 0%;
background-color: blue;
}
100% {
background-color: blue
}
}
<section id="popularity">
<div class="animation ">
<h2>Most popular books</h2>
<div class='tr-box'>
<table>
<tr>
<td>The Snowman</td>
<td>
<div class="a-box-animation">
</div>
</td>
</tr>
</table>
</div>
</div>
</section>
=======
最佳答案
您可以向滚动事件添加事件处理程序,并在滚动时检查元素是否在视口(viewport)中。如果是,则向其添加一个额外的类以启用其动画。
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
$(window).scroll(function() {
if (isElementInViewport($('.box'))) {
$('.box').addClass('animate')
}
})
您需要将通用的 css 样式提取到类 box
中,并将有关动画的样式放入类 animate
中。
关于javascript - 滚动时动画开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627486/