我想使用JQuery .animate()
创建一个连续的动画效果,其方向是从数组创建的。这是我到目前为止成功做到的:
var animation = [{"top":80},{"left":130},{"top":200},{"left":0},{"top":0}];
$.each(animation, function(i) {
$('div').animate(animation[i], 1000);
});
但是,我想在每个元素属性中保存数组,如下所示:
<div data-animation='[{"top":80},{"left":130},{"top":200},{"left":0},{"top":0}]'></div>
<div data-animation='[{"top":50},{"left":-30},{"top":100},{"left":80},{"top":75}]'></div>
<div data-animation='[{"top":10},{"left":-30},{"top":100}]'></div>
...所以我希望我可以用不同的方向动画多个元素。但我不知道如何将属性值转换为对象数组(我希望我可以在没有插件的情况下执行此操作):
$('div').each(function() {
var animation = $(this).data('animation'), // How to convert this into an array?
$animatedbox = $(this);
$.each(animation, function(i) {
$animatedbox.animate(animation[i], 1000);
});
});
以下是演示: http://jsfiddle.net/wthLR/
答案 0 :(得分:2)
试试这个:
$('div').each(function(){
var $div = $(this);
var animation = eval($div.attr('data-animation'));
$.each(animation, function(i) {
$div.animate(animation[i], 1000);
});
});
答案 1 :(得分:2)
$('div').each(function() {
var animation = eval($(this).attr('data-animation')),
$animatedbox = $(this);
$.each(animation, function(i) {
$animatedbox.animate(animation[i], 1000);
});
});
这有效
答案 2 :(得分:1)
如果你不想使用邪恶的eval
函数,你可以使用它:
$('div').each(function () {
var $div = $(this);
var data = $div.data('animation').replace(/[[\]]/g,'');
var dataArray = data.split(',');
var animations = {};
for (var i = 0; i < dataArray.length; i++) {
var trimBrackets = dataArray[i].replace(/[{\}]/g,'');
var keyValues = trimBrackets.split(':');
var key = keyValues[0].replace(/\'/g, '');
var value = parseInt(keyValues[1], 10);
animations[i] = {};
animations[i][key] = value;
}
$.each(animations, function (i, v) {
$div.animate(v, 1000);
});
});