水杯注水动画示例
当前好多使用到css动画的场景,并且需要鼠标控制动画的播放或暂停,如上图所示,点击水龙头时出水,松开鼠标停止出水,保持停止时的状态。接下来要介绍的便是一种脱离JS,使用纯CSS属性来写动画并控制播放暂停。
本案例效果
<div class="bollbox">
<div class="boll"></div>
</div>
.bollbox{
border-bottom: 3px solid #ccc;
border-right: 3px solid #ccc;
width: 450px;
}
.boll {
margin: 30px 0 0;
width: 150px;
height: 150px;
background-color: #4158D0;
background-image: linear-gradient(43deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
border-radius: 50%;
}
在CSS中添加动画
.bollbox{
border-bottom: 3px solid #ccc;
border-right: 3px solid #ccc;
width: 450px;
}
.boll {
margin: 30px 0 0;
width: 150px;
height: 150px;
background-color: #4158D0;
background-image: linear-gradient(43deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
border-radius: 50%;
+ animation: run 1s linear; // run动画,1秒,匀速
+ animation-fill-mode: forwards; // 状态停留在最后一帧
}
+ @keyframes run {
+ to{
+ transform: translateX(300px) rotate(360deg);
+ }
+ }
此时小球动了起来,效果如下:
<div class="bollbox">
+ <button type="button" class="btn">按住开始,松开停止</button>
<div class="boll"></div>
</div>
.bollbox{
border-bottom: 3px solid #ccc;
border-right: 3px solid #ccc;
width: 450px;
}
.boll {
margin: 30px 0 0;
width: 150px;
height: 150px;
background-color: #4158D0;
background-image: linear-gradient(43deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
border-radius: 50%;
animation: run 1s linear;
animation-fill-mode: forwards;
+ animation-play-state: paused; // 起始状态,暂停
}
@keyframes run {
to{
transform: translateX(300px) rotate(540deg);
}
}
+ .btn:active +div{ // 激活状态下,执行动画
+ animation-play-state: running;
+ }
OK,此时便完成了本案例。
本案例主要用到了CSS3的几个动画属性,如animation-play-state
、animation-fill-mode
等,合理的运用这些简单的CSS便可以完成一些有意思的效果,下期再见。