CSS3 常见的动画效果

7,017 阅读2分钟

前言

由于 CSS3 的推出,让有些动画不在以 JS 来实现,仅仅依靠 CSS 就可以实现许多动画效果。提高了性能同时,又增加了很多趣味性。 接下来我会持续更新大家常用到的CSS效果,供大家学习。。。

例子

一,皮球掉地上反弹起来

效果

// html

<div class="ball"></div>

//css

@keyframes bounce {
60%, 80%, to {
  transform: translateY(400px); 
  animation-timing-function: ease;        
  }        
  70% { transform: translateY(300px); }        
  90% { transform: translateY(360px); }
}

.ball {
    width: 50px;        
    height: 50px;        
    border-radius: 50%;
    margin: auto;        
    background: rgba(0,100,100,0.5);        
    animation: bounce 2s cubic-bezier(.58,.13,.94,.64) forwards;
}

技术分析:主要技术点是利用贝塞尔曲线 和 ease 来控制动画速度,tansition-timing-function 还有 linear 属性。

二,纯 CSS 实现 gif 效果

效果

// html

    <div id="frame"></div>
// css
#frame {
  width: 50px;
  height: 72px;
  border: 1px solid transparent;  
  background: url(https://s.cdpn.io/79/sprite-steps.png) no-repeat left top;
  animation: frame-animation 1s steps(10) infinite;    
}

@keyframes frame-animation {
  0% { background-position: 0px 0; }
  100% { background-position: -500px 0; }
}

技术分析:主要技术点是 steps(10) ,实现原理是,图片分为 10 部分,总共需要 10 步来完成,其中动画不是滑动实现的,而是每一步只显示一个页面。注意:steps(number) 中的 number*(每小张图片的长度)=== 图片总长度相对应,才能实现 gif 效果。

三,图片移动

效果

// html

  <div class="pic"></div>

// css

@keyframes panoramic {
    to { background-position: 100% 0; }
}

.pic {
    width: 150px; height: 150px;
    background: url('http://c3.staticflickr.com/3/2671/3904743709_74bc76d5ac_b.jpg');
    background-size: auto 100%;     
    animation: panoramic 10s linear infinite alternate;
    animation-play-state: paused;
}

.pic:hover, .pic:focus {
    animation-play-state: running;
}

技术分析: 主要技术点是 animation-play-state: paused 暂停动画。

四,实现打字输入效果

效果

// html 

  <h1 class="pic">CSS is awesome!</div>

// css

@keyframes typing {
    from { width: 0 }
}

/* 光标 */
@keyframes caret {
    50% { border-right-color: transparent; }
}

h1 {
    font: bold 200% Consolas, Monaco, monospace;
    width: 15ch;
    white-space: nowrap;
    overflow: hidden;
    border-right: .05em solid;
    animation: typing 8s steps(15),
                caret 1s steps(1) infinite;

}

技术分析:CH宽度单位是每个字体长度,还是利用了 steps() 一次只显示一个特性,而不是滑动,可以把 step() 换成其他属性如:linear,ease等