translate3dのサンプル

by FiNGAHOLiC

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div class="boxNormal"></div>
<div class="boxDelay"></div>

CSS

.boxNormal,
.boxDelay{
    width:100px;
    height:100px;
    position:absolute;
    left:0;
    z-index:1;
}
.boxNormal{
    top:0;
    background:#000;
}
.boxDelay{
    bottom:0;
    background:#c00;
}

JavaScript

// $.fn.cssにはdelayは効かない(擬似的には出来るけど)ので
// 代替えの関数を用意しておく
$.timeout = function(delay){
    var delay = delay || 0;
    return $.Deferred(function(defer){
        var timer = setTimeout(function(){
            clearTimeout(timer);
            defer.resolve();
        }, delay);
    }).promise();
};

$(function(){
    
    var $boxNormal = $('.boxNormal');
    var $boxDelay = $('.boxDelay');

    // delayなしの普通のアニメ
    $boxNormal.css({
        '-webkit-transform' : 'translate3d(200px, 0, 0)', // 必ずpxをつける
        '-webkit-transition' : 'all 5000ms linear' // 必ずmsをつける
    }).on('webkitTransitionEnd', function(){ // コールバック
        window.alert('normal animation done!');
        // 後々のものに影響する可能性があるのでtransitionはクリアしておく
        // また、webkitTransitionEndは毎回溜まっていくので必ずアンバインドしておく
        $(this)
            .off('webkitTransitionEnd')
            .css('-webkit-transition', '');
    });
    
    // delayをつけてアニメ
    $.timeout(5000).done(function(){
        $boxDelay.css({
            '-webkit-transform' : 'translate3d(200px, 0, 0)',
            '-webkit-transition' : 'all 5000ms linear'
        }).on('webkitTransitionEnd', function(){
            window.alert('delayed animation done!');
            $(this)
                .off('webkitTransitionEnd')
                .css('-webkit-transition', '');
        });
    });
    
});