百分比图表 CSS3 动画,从视图开始,滚动后开始,而不是在页面加载时



我在使用圆形动画时遇到问题。CSS 动画工作正常,但我无法让它在元素视图而不是所有页面的加载上工作。

我已经在stackoverflow上经历了很多问题,但无论如何都无法获得这项工作,我不确定到底出了什么问题,但是当我称动画类为".slice-right"时,没有任何反应,但是,如果该类只是插入到HTML中,一切都很好。

此外,浏览器的控制台不会显示错误。

任何人都可以完成这项工作吗?

多谢。

<head>
<link rel="stylesheet" type="text/css" href="charts.css">
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="charts.js"></script>
</head>
<body>
<div class="content"></div>
<div class="xc-one-chart">
<h1>
hello
</h1><div class="pie">
<div class= "right"></div>
<div class="percent">
<div class="number">100%</div>
</div>
</div>
</div>
</body>

.css

.content{
height:0px
}
.pie {
display:inline-block;
position: relative;
width: 1em;
height: 1em;
background-color:transparent;
font-size: 7em;
text-align: center;
border-radius:50%;
}
.right {
position: absolute;
z-index: 11;
background-color: #ff5252;
width: 100%;
height: 100%;
clip: rect(0, 0.5em, 0.5em, 0.5em);
border-radius:50%;
}

.percent {
position: absolute;
z-index: 20;
top: 3px;
right: 3px;
bottom: 3px;
left: 3px;
background: #1d2225;
border-radius:50%;
}

.number {
position: absolute;
z-index: 30;
width: 100%;
height: 100%;
padding-top: 50%;
line-height: 0;
font-size: .3em;
color:white;
}
.slice-right{
-webkit-animation-delay: 1.2s;
-webkit-animation-duration: 0.3s;
-webkit-animation-name: right-slice;
-webkit-animation-iteration-count: 1;
-webkit-animation-fill-mode: forwards; 
}

@-webkit-keyframes right-slice {
from {
clip: rect(0, 50%, 0.5em, 0.5em);
}
50% {
clip: rect(0, 1em, 0.5em, 0.5em);
}
to {
clip: rect(0, 1em, 1em, 0.5em);
}
}

JavaScript

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 = $('.pie .right');
// If the animation has already been started
if ($elem.hasClass('slice-right')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('slice-right');
}
}
// Capture scroll events
$(window).scroll(function(){
checkAnimation();
});

这不起作用的原因是没有滚动的位置,因此不会触发滚动事件。添加一些空间以便您可以滚动使代码正常工作。

.content{
height:500px /*add space*/
}

小提琴:https://jsfiddle.net/ekgugx76/1/

相关内容

最新更新