jquery - 在 jQuery 中执行动画时如何使用元素的属性?

标签 jquery animation

如果我有大量元素,可能看起来像:

<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/

相关文章:

javascript - 高分子曲线运动路径

swift - 你能让一个类的所有对象通过一个方法调用做同样的事情吗?

javascript - 垂直滑过整个页面

javascript - 如何使 tbody 子级大小与 thead 之后创建的第一个 tbody 大小相同

javascript - 使用 jQuery 执行此简单过滤器的更好方法是什么

javascript - 使用 jQuery 通过 Ajax 将数据从 javascript 发送到 php。如何查看回数据?

swift - 使用在矩形中绘制对 UIView 中的属性进行动画处理

javascript - 切换变量以更改 href

javascript - 如何使用 jQuery 和 CSS 显示容器

javascript - 使用 jQuery/Javascript 编辑 CSS3 动画