且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS:动画vs.转换

更新时间:2023-02-16 21:40:43

看起来你有一个关于如何做的句柄,

状态和结束状态。像抽屉菜单一样,开始状态可以打开,结束状态可以关闭,反之亦然。

如果要执行 具体涉及开始状态和结束状态,或者您需要对转换中的关键帧进行更细致的粒度控制,那么您必须使用动画。


So, I understand how to perform both CSS3 transitions and animations. What is not clear, and I've googled, is when to use which.

For example, if I want to make a ball bounce, it is clear that animation is the way to go. I could provide keyframes and the browser would do the intermediates frames and I'll have a nice animation going.

However, there are cases when a said effect can be achieved either way. A simple and common example would be implement the facebook style sliding drawer menu:

This effect can be achieved through transitions like so:

.sf-page {
    -webkit-transition: -webkit-transform .2s ease-out;
}

.sf-page.out {
    -webkit-transform: translateX(240px);
}

http://jsfiddle.net/NwEGz/

Or, through animations like so:

.sf-page {
    -webkit-animation-duration: .4s;
    -webkit-transition-timing-function: ease-out;
}

.sf-page.in {
    -webkit-animation-name: sf-slidein;
    -webkit-transform: translate3d(0, 0, 0);
}

.sf-page.out {
    -webkit-animation-name: sf-slideout;
    -webkit-transform: translateX(240px);
}

@-webkit-keyframes sf-slideout {
    from { -webkit-transform: translate3d(0, 0, 0); }
    to { -webkit-transform: translate3d(240px, 0, 0); }
}

@-webkit-keyframes sf-slidein {
    from { -webkit-transform: translate3d(240px, 0, 0); }
    to { -webkit-transform: translate3d(0, 0, 0); }
}

http://jsfiddle.net/4Z5Mr/

With HTML that looks like so:

<div class="sf-container">
    <div class="sf-page in" id="content-container">
        <button type="button">Click Me</button>
    </div>
    <div class="sf-drawer">
    </div>
</div>

And, this accompanying jQuery script:

$("#content-container").click(function(){
    $("#content-container").toggleClass("out");
    // below is only required for css animation route
    $("#content-container").toggleClass("in");
});

What I'd like to understand is what are the pros and cons of these approaches.

  1. One obvious difference is that animating is taking a whole lot more code.
  2. Animation gives better flexibility. I can have different animation for sliding out and in
  3. Is there something that can be said about performance. Do both take advantage of h/w acceleration?
  4. Which is more modern and the way going forward
  5. Anything else you could add?

It looks like you've got a handle on how to do them, just not when to do them.

A transition is an animation, just one that is performed between two distinct states - i.e. a start state and an end state. Like a drawer menu, the start state could be open and the end state could be closed, or vice versa.

If you want to perform something that does not specifically involve a start state and an end state, or you need more fine grain control over the keyframes in a transition, then you've got to use an animation.