【发布时间】:2019-06-04 18:36:34
【问题描述】:
我有一个圆形图,我正在尝试在上面测试动画。我在显示 onScroll 的图表时遇到问题。我已经能够在滚动上添加整个对象加载,但是动画在整个对象加载之前开始。有没有一种方法只能在用户滚动到对象后才启动橙色条?
CSS
.single-chart {
width: 33%;
justify-content: space-around ;
}
.circular-chart {
display: block;
margin: 10px auto;
max-width: 80%;
max-height: 250px;
}
.circle-bg {
fill: none;
stroke: #eee;
stroke-width: 3.8;
}
.circle {
fill: none;
stroke-width: 2.8;
stroke-linecap: round;
animation: progress 1s ease-out forwards;
}
.circular-chart.onScroll {
animation: progress .9s;
}
@keyframes progress {
0% {
stroke-dasharray: 0 100;
}
}
.circular-chart.orange .circle {
stroke: #ff9f00;
}
.percentage {
fill: #666;
font-family: sans-serif;
font-size: 0.5em;
text-anchor: middle;
}
HTML
<div class="single-chart" style="padding-top:500px;">
<svg viewBox="0 0 36 36" class="circular-chart orange">
<path class="circle-bg"
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
/>
<path class="circle"
stroke-dasharray="30, 100"
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
/>
<text x="18" y="20.35" class="percentage">30%</text>
</svg>
</div>
jQuery
<script>
var scrollpos = window.scrollY; // window scroll position
var wh = window.innerHeight-50; // as soon as element touches bottom with offset event starts
var element = document.querySelector(".circular-chart"); //element
window.addEventListener('scroll', function(){
if(scrollpos > (element.offsetTop - wh)){
element.classList.add("onScroll");
}
});</script>
【问题讨论】:
-
SVG 没有 offsetTop,所以我使用
element.getBoundingClientRect();来获取元素相对于视口左上角的底部位置 - 并检查它是否小于窗口的当前高度(注意我还将类添加到.circle而不是.circular-chart,并修改了CSS 以反映这一点):codepen.io/anon/pen/WLgGaL -
哦,明白了!非常感谢您对此@mark.hch 的帮助!
-
这个方法只适用于动画 .circle 的第一个实例,对吧?
-
从技术上讲,只是因为您使用的是
querySelector,它只选择选择器匹配的第一个元素。如果将它们分配给单独的变量,则没有理由不能处理圆的多个实例。我更新了同一支笔:codepen.io/anon/pen/WLgGaL -
有道理,谢谢!在您看来,您认为这是否有效,还是您更愿意使用不同的方法?
标签: jquery svg css-animations