这要求使用JavaScript或jQuery捕获滚动事件,并在每次触发滚动事件时检查该元素是否在视图中。
看到元素后,开始动画。在下面的代码中,这是通过向元素添加“开始”类来触发动画来完成的。
<div class="bar">
<div class="level eighty">80%</div>
</div>
.eighty.start {
width: 0px;
background: #aae0aa;
-webkit-animation: eighty 2s ease-out forwards;
-moz-animation: eighty 2s ease-out forwards;
-ms-animation: eighty 2s ease-out forwards;
-o-animation: eighty 2s ease-out forwards;
animation: eighty 2s ease-out forwards;
}
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round( $elem.offset().top );
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.bar .level');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
}
// Capture scroll events
$(window).scroll(function(){
checkAnimation();
});