jQuery 动画动态转换

jQuery Animate Dynamic Transformation

我是 jQuery 的新手,正在构建一个基本块,如果我按左键,它会向左移动;如果我按右,则向右移动。它工作得很好。但是,我不想直接使用 css webkitTransform,而是想使用动画来使运动更流畅。这是我的初始代码:http://jsfiddle.net/hphchan/c2zzhjwL/

我整天都在浏览如何做到这一点,但仍然找不到答案。我注意到 jQuery 和 step 函数有一个 .animate() 内置方法。但是,我不知道该怎么做才能让它发挥作用。

谢谢。

使用 .animate 你可以替换

$spinner.css("webkitTransform", "translate(" + i + "px, 0)");

$spinner.animate({ left: i }, {
       duration: 500, //change this according to your need
       step: function(now, fx){
            $spinner.css("margin-left", now);
       }
});

DEMO

Article if you want more in detail

您为微调器设置动画的时间非常少,我建议使用 CSS 来获得相同的结果,这里是 example

#spinner {
   width : 50px;
   height : 10px;
   background-color : #000;
   -webkit-transition: all .6s; /* Safari */
   transition: all .6s;
}

对于 animate 你可以使用 :

$spinner.animate({
    left: i
}, 200); 

为此,您必须将 #spinner 的位置设置为相对或绝对。如果你想创建一个游戏,这对 hitbox 很有用。

Demo here