jQuery animate transform翻译x,y

时间:2013-04-09 22:51:27

标签: jquery

我需要为图像设置动画,但我想使用CSS转换。我发现了之前的问题解决方案是这样的:

jsFiddle

我这样修改:

jsFiddle

我不知道如何传递x和y值,因为我需要翻译(x,y)。

这种方式不起作用:

$('#box').animate({  fake: [100,50] }, {
    step: function(now,fx) {
       $(this).css('-webkit-transform','translate(' + now[0] + 'px,' + now[1] + 'px)'); 
    },
    duration:'slow'
},'linear');

3 个答案:

答案 0 :(得分:2)

;(function($) {
            var delay = 0;
            $.fn.translate3d = function(translations, speed, easing, complete) {
                var opt = $.speed(speed, easing, complete);
                opt.easing = opt.easing || 'ease';
                translations = $.extend({x: 0, y: 0, z: 0}, translations);

                return this.each(function() {
                    var $this = $(this);

                    $this.css({ 
                        transitionDuration: opt.duration + 'ms',
                        transitionTimingFunction: opt.easing,
                        transform: 'translate3d(' + translations.x + 'px, ' + translations.y + 'px, ' + translations.z + 'px)'
                    });

                    setTimeout(function() { 
                        $this.css({ 
                            transitionDuration: '0s', 
                            transitionTimingFunction: 'ease'
                        });

                        opt.complete();
                    }, opt.duration + (delay || 0));
                });
            };
        })(jQuery);

这样你也可以使用translateZ;

来源http://cameronspear.com/blog/animating-translate3d-with-jquery/

答案 1 :(得分:1)

$('#box').animate({  fake: 200, fake2: 10 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','translate('+now+'px,'+now+'px )'); 
    },
    duration:'slow'
},'linear');

jsFiddle

答案 2 :(得分:1)

这种方式似乎有效但可能存在更好的解决方案

jsfiddle example

var offX, offY;

$('#box').animate({  fake1: 150, fake2: 100 }, {
  step: function(now,fx) {

    if (fx.prop === "fake1") {
      offX = now;
    } else if (fx.prop === "fake2") {
      offY = now;
      $(this).css('-webkit-transform','translate('+ offX +'px,'+ offY +'px)');
    }
  },
  duration:300
},'linear');