【问题标题】:Animate element by mouseover and animate.css通过 mouseover 和 animate.css 动画元素
【发布时间】:2016-12-30 19:53:43
【问题描述】:

是否可以通过鼠标悬停和animate.css为元素设置动画?

$(document).ready(function(){
    $("p").mouseover(function(){
        $("p").css("background-color", "red");
        $("#mystyle").animateCss('bounce');
    });
    $("p").mouseout(function(){
        $("p").css("background-color", "gray");
    });
});

我试过了,但出了点问题。 https://jsfiddle.net/f79b7033/

【问题讨论】:

  • 如果你想使用animateCss 函数,你需要将它包含在你的代码中。检查我的答案:)

标签: jquery css animate.css


【解决方案1】:

根据documentation in animation.css,您可以使用以下方式扩展jQuery:

$.fn.extend({
    animateCss: function (animationName) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        this.addClass('animated ' + animationName).one(animationEnd, function() {
            $(this).removeClass('animated ' + animationName);
        });
    }
});

而且你没有在代码中添加它。

这是一个工作示例(包括上面的代码):
https://jsfiddle.net/dekelb/9jaq7fhr/

【讨论】:

    【解决方案2】:

    我对 animate.css 不熟悉,但是打开控制台会出现错误:

    Uncaught TypeError: $(...).animateCss is not a function
        at HTMLParagraphElement.<anonymous> ((index):53)
        at HTMLParagraphElement.dispatch (jquery-3.1.1.js:5201)
        at HTMLParagraphElement.elemData.handle (jquery-3.1.1.js:5009)
    

    所以我查看了 animate.css 的文档,发现:

    $('#yourElement').addClass('animated bounceOutLeft');

    添加了它,这是你的小提琴 - 看起来它正在工作:

    https://jsfiddle.net/f79b7033/3/

    编辑: Dekel 指出,上述错误是由于没有扩展 Jquery 引起的(请参阅他的答案以了解如何做到这一点)。这是非 jQuery 版本。

    【讨论】:

    • 使用addClass 是一个选项,但如果你想使用animateCss 函数,你需要扩展jQuery。阅读我的答案以获取有关此的更多信息。
    • @Dekel 有道理。猜猜我对文档的阅读不够深入:) 赞成你的答案,因为它是更好的答案,我会进行编辑,解释我的做法是非 Jquery 方式
    猜你喜欢
    • 2012-10-06
    • 2016-12-16
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2016-04-09
    • 2016-03-12
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多