如果我有大量元素,可能看起来像:
<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()
最佳答案
您必须迭代这些元素:
$('.test').each(function() {
var $this = $(this);
$this.animate({
left: +$this.attr('data-left'),
bottom: +$this.attr('data-bottom')
});
});
我认为您可能还必须将无单位字符串解析为数字。
关于jquery - 在 jQuery 中执行动画时如何使用元素的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14851920/