2013-02-13 24 views
2

如果我有元素的負荷,這可能看起來像:如何在jQuery上對其執行動畫時使用元素屬性?

<p class="test" data-left="250" data-bottom="55">Good morning.</p> 
<p class="test" data-left="350" data-bottom="123">Good afternoon.</p> 
<p class="test" data-left="290" data-bottom="300">Good night.</p> 

...等等,我怎麼能動畫呢?我最初嘗試:

$('.test').animate({ 
    left: $(this).attr('data-left'), 
    bottom: $(this).attr('data-bottom') 
}); 

但似乎$(this)上下文不是就在這裏。有沒有辦法做到這一點?或者只是寫一個.each()循環來實現它的情況?

注:我們使用的是舊版本的jQuery的,因此使用的.attr()

回答

2

你必須遍歷這些元素:

$('.test').each(function() { 
    var $this = $(this); 

    $this.animate({ 
     left: +$this.attr('data-left'), 
     bottom: +$this.attr('data-bottom') 
    }); 
}); 

我想你可能不得不將無單位的字符串解析爲數字。

+0

不解析字符串,但喲,非常感謝。似乎有$(this)可以方便地在那裏!呃,好吧 – LeonardChallis 2013-02-13 11:19:57

0

您需要使用.each()

$('.test').each(function(){ 
    $(this).animate({ 
      left:$(this).attr('data-left'), 
      bottom:$(this).attr('data-bottom') 
    }) 
}); 
相關問題