Jquery 动画方法在 concat 后无法识别 属性

Jquery animate method not recognising property after concat

我创建了一个 animate() 方法,它从被点击元素的 data- 属性获取动画的推动方向和时间:

HTML

<div class="caja" data-empuje="top" data-tiempo="500">Caja 1</div>
<div class="caja" data-empuje="left" data-tiempo="100">Caja 2</div>
<div class="caja" data-empuje="right" data-tiempo="400">Caja 3</div>
<div class="caja" data-empuje="bottom" data-tiempo="900">Caja 4</div>

JS

$('.caja').on('click', function(){

            var empuje = $(this).data('empuje');
            var tiempo = $(this).data('tiempo');

            var stringEmpuje = "margin-" + empuje;      //alerts correctly (for example, 'margin-top')

            $(this).animate({
                stringEmpuje: '-=40px',
                opacity: 0
            }, tiempo);
        });

时间正确,但方向不适用,即使 stringEmpuje var 正确提醒最终字符串,应该被 jQuery 识别为 CSS 属性 , 但不适用。

LIVE DEMO

您似乎正试图将 stringEmpuje 的值作为键传递给 animate 方法。如果是这样,试试这个:

$('.caja').on('click', function(){

    var empuje = $(this).data('empuje');
    var tiempo = $(this).data('tiempo');

    var stringEmpuje = "margin-" + empuje;
    var animOptions = {
        opacity: 0
    };
    animOptions[stringEmpuje] = '-=40px';

    $(this).animate(animOptions, tiempo);
});

使用 ES2015 你可以简单地做:

$('.caja').on('click', function(){

    var empuje = $(this).data('empuje');
    var tiempo = $(this).data('tiempo');

    var stringEmpuje = "margin-" + empuje;

    $(this).animate({
        [stringEmpuje]: '-=40px',
        opacity: 0
    }, tiempo);
});