在jquery animate中使用数据字符串作为属性

时间:2015-11-25 01:06:44

标签: jquery jquery-animate

我正在向函数返回一个方向字符串,我希望用返回值中的字符串替换jquery animate的left属性。

我尝试了以下无效的

// my attempt at using string returned for property
        function direction (data) {
           // move the object in the direction given by x
            $( "#cube" ).animate({
                data.direction: "+=5" // here changed from left -> data.direction which has the direction string inside [left up right down] 
              }, 10, function() {
            // Animation complete.
            });
        }


// original working example
    function direction (data) {
       // move the object in the direction given by x
        $( "#cube" ).animate({
            left: "+=5"
          }, 10, function() {
        // Animation complete.
        });
    }

1 个答案:

答案 0 :(得分:1)

尝试创建属性设置为data.direction的对象,将值设置为"+=5"

   function direction (data) {
     var opts = {}; opts[data.direction] = "+=5";
     // move the object in the direction given by x
     $( "#cube" ).animate(opts, 10, function() {
       // Animation complete.
     });
   }

可选地,

var data = {
  left:{left:""},
  right:{right:"+=5"},
  up:{up:""},
  down:{down:""}
}

function direction (data) {
  // move the object in the direction given by x
  $( "#cube" ).animate(right, 10, function() {
    // Animation complete.
  });
}

direction(data.right)