使用CSS的jQuery自定义数据属性

时间:2011-12-16 16:15:11

标签: javascript jquery html5 css3 jquery-animate

我正在使用animate.css,现在我有 animated2500 的CSS样式,这意味着动画需要2.5秒。风格是:

.animated2500 {
    -webkit-animation: 2500ms ease;
    -moz-animation: 2500ms ease;
    -ms-animation: 2500ms ease;
    animation: 2500ms ease;
}

所以在我的HTML中我会这样做:

<p class="animated2500 pulse">Takes 2.5 seconds to pulse</p>

必须有一种更简单的方法来做到这一点,因为我想要指定每次为它创建一个自定义类的秒数。

有没有办法使用自定义数据属性,如:<p data-delay="5000" class="fade">Fade in 5 econds</p>会起作用吗?

我怎么能做到这样的事情?

谢谢!

3 个答案:

答案 0 :(得分:1)

我不认为你可以使用纯CSS,个人风格是可行的方法。

如果你真的想使用data-*属性,因为你已经标记了你的问题jquery,我会发布一个特定于jQuery的答案,尽管CSS动画和数据属性并不是特定于jQuery的(甚至是JavaScript):

jQuery(function($) {
    $(".pulse[data-delay]").each(function() {
        var value = parseInt(this.getAttribute("data-delay"), 10);
        if (!isNaN(value)) {
            value = value + "ms ease";
            this.style["-webkit-animation"] = value;
            this.style["-moz-animation"] = value;
            this.style["-ms-animation"] = value;
            this.style["animation"] = value;
        }
    });
});

它遍历DOM准备好的元素并直接应用样式。我不喜欢它有几个原因(尤其是加载到页面后加载的新元素将无法处理),但如果你真的,真的不想创建特定的类......

答案 1 :(得分:0)

这样的事可能有用吗? (另)

$(document).ready(function() {
    $("p[data-delay]").each(function(){
        $(this).css('-webkit-animation',$(this).attr('data-delay')+'ms ease');
        $(this).css('-moz-animation',$(this).attr('data-delay')+'ms ease');
        $(this).css('-ms-animation',$(this).attr('data-delay')+'ms ease');
        $(this).css('animation',$(this).attr('data-delay')+'ms ease');
        }
    );
});

答案 2 :(得分:0)

$(document).ready(function() {
    $("p[data-delay]").each(function(){
        this.style.webkitAnimationDuration = $(this).attr('data-delay') + 's';
    );
});