任务
我们最近在 SeatGeek 更新了我们的 "跟踪" 图标, 以匹配我们的新 iPhone 应用程序. 首席设计师在 PSD 中创建了具有不同状态的心脏图标, 并在下面创建了动画:
什么是 CSS3 动画?
在 CSS 中, 动画是一种让元素逐渐改变样式的效果. 您可以使用 @keyframes 关键字创建动画, 后跟动画的名称.
- @keyframes heartAnimation {
- /* Animation code goes here */
- }
要使动画跨浏览器兼容, 您需要使用供应商前缀:
- @keyframes heartAnimation {
- /* IE 10+ */
- }
- @-webkit-keyframes heartAnimation {
- /* Safari 4+ */
- }
- @-moz-keyframes heartAnimation {
- /* Fx 5+ */
- }
- @-o-keyframes heartAnimation {
- /* Opera 12+ */
- }
但是, 对于本文的其余部分, 我将为了空间而排除供应商前缀.
下一步是添加动画效果并确定它们何时发生. 您可以使用 0%到 100%的百分比或使用 "from" 和 "to" 关键字来执行此操作, 只需使用起始和结束状态的简单动画. 下面是将背景颜色从黄色变为蓝色, 然后从黄色变为绿色变为蓝色的示例.
- @keyframes colorChange {
- from {background: yellow;}
- to {background: blue;}
- }
- @keyframes colorChange {
- 0% {background: yellow;}
- 50% {background: green;}
- 100% {background: blue;}
- }
创建关键帧后, 您可以将动画称为 CSS 属性. 例如, 下面的代码将运行 colorChange 动画 2 次以上, 持续时间为 2 秒:
- .color-animation {
- animation-name: changeColor;
- animation-iteration-count: 2;
- animation-duration: 2s;
- }
- /* Shorthand */
- .color-animation {
- animation: changeColor 2 2s;
- }
计划动画
在看了几次 gif 之后, 我意识到它是一个轻微的收缩, 然后扩展到比原始尺寸略大的尺寸, 然后回到原来的尺寸.
Heart 点击动画
使用上面的 CSS3 关键帧和动画语法, 这里是我用来在本页顶部的 gif 中制作动画的代码. 它使用 CSS 变换和属性来缩放图像.
- @keyframes heartAnimation {
- 0% {transform: scale(1,1)}
- 20% {transform: scale(0.9,0.9)}
- 50% {transform: scale(1.15,1.15)}
- 80% {transform: scale(1,1)}
- }
- .toggle-animation {
- animation: heartAnimation 0.7s; // no iteration count is needed as the default is 1 time
- }
对于图像, 我使用的是精灵, 所以我还需要更改图像的位置以获得红色背景:
- .toggle-animation {
- background: url('../images/animation-example-sprite.png') no-repeat -320px 0;
- animation: heartAnimation 0.7s; // no iteration count is needed as the default is 1 times
- }
Loading 动画
对于一个加载状态, 我让心脏发白并且无限地脉动 in-and-out. 它还缩小并缩小到原始大小, 而不是像上面的 heartAnimation 代码那样在进入原始状态之前略大于原始大小. 以下是加载状态的代码:
- @keyframes loading {
- 0% {transform: scale(1,1) }
- 50% {transform: scale(0.8,0.8) }
- 100% {transform: scale(1,1) }
- }
- /* Notice the added 'infinite' to is used to make the animation-iteration-count */
- .toggle-loading {
- background: url('../images/animation-example-sprite.png') no-repeat -160px 0; // make background white
- animation: loading 1s infinite;
- -webkit-animation: loading 1s infinite;
- -moz-animation: loading 1s infinite;
- -o-animation: loading 1s infinite;
- }
查看动画的演示
下面是我用来点击每个图标时动画的 JS. JS 添加并删除了我添加动画属性的类.
- $(document).ready(function(){
- $('.animation-1 .image').on('click', function(){
- $(this).toggleClass('toggle-animation');
- });
- $('.animation-2 .image').on('click', function(){
- $(this).toggleClass('toggle-animation-slow');
- });
- $('.animation-3 .image').on('click', function(){
- $(this).toggleClass('toggle-loading');
- });
- });
来源: http://www.jianshu.com/p/5b0992ed3f78