【发布时间】:2015-11-16 01:39:33
【问题描述】:
我正在尝试使用 CSS 动画制作进度指示器 div。请参考链接的JSBin。我想要实现的行为是,当用户在 stage1 之后点击 stage3 时,div 宽度应该从当前的 30% 增加到 100%,而不是像现在这样从 0% 开始。我知道如果我将 0% 值设置为宽度:30%,我可以得到。但如果我有很多阶段,它就不会那么好。我希望动画从最后阶段的最终宽度开始到新阶段中指定的宽度。
document.getElementById('stage1').addEventListener('click', function() {
document.getElementById('progress').classList.add('stage1');
}, false);
document.getElementById('stage2').addEventListener('click', function() {
document.getElementById('progress').classList.add('stage2');
}, false);
document.getElementById('stage3').addEventListener('click', function() {
document.getElementById('progress').classList.add('stage3');
}, false);
.progress-wrapper {
height: 10px;
width: 400px;
background-color: #BBDEFB;
}
#progress {
background-color: #AADE00;
height: 10px;
width: 0;
}
.stage1 {
animation-name: stage1;
animation-duration: 1s;
animation-fill-mode: forwards;
}
@keyframes stage1 {
to {
width: 30%;
}
}
.stage2 {
animation-name: stage2;
animation-duration: 1s;
animation-fill-mode: forwards;
}
@keyframes stage2 {
to {
width: 70%;
}
}
.stage3 {
animation-name: stage3;
animation-duration: 1s;
animation-fill-mode: forwards;
}
@keyframes stage3 {
to {
width: 100%;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="progress-wrapper">
<div id="progress"></div>
</div>
<pre>
</pre>
<button id="stage1">stage1</button>
<button id="stage2">stage2</button>
<button id="stage3">stage3</button>
</body>
</html>
【问题讨论】:
-
当多个动画涉及使用相同的属性时,CSS 将使用最新的并覆盖最后的。这几乎类似于这种行为:stackoverflow.com/questions/32224802/…
-
@ManojKumar 谢谢。我将不得不考虑一种不同的方法,宽度的起始值和最终值的组合太多了。
-
是的,我建议你使用 Greensock Tweenmax/Timelinemax 库。这很简单,符合您的要求。
标签: javascript css html css-animations