简体   繁体   English

使用addClass和removeClass的jQuery CSS动画

[英]jQuery CSS animations with addClass and removeClass

So, I have now made jQuery Ajax code that checks that the username and password are correct. 所以,我现在已经制作了jQuery Ajax代码,用于检查用户名和密码是否正确。 But instead of just displaying a error message, I'd like to shake the element as well. 但是,我不想只显示错误信息,而是想要动摇元素。

Define Shake? 定义摇动?

That kind of shake that wordpress has. wordpress所具有的那种震动。 Go to wordpress.com/wp-login.php and fill there some random info and the element shakes. 转到wordpress.com/wp-login.php并在那里填写一些随机信息,元素会震动。

That shake can be done by Animate.css . 这种震动可以通过Animate.css完成。

What's the problem then? 那有什么问题呢?

When the login fails, jQuery makes this. 当登录失败时,jQuery会这样做。

$('.element').addClass('shake');

But because the shake element has CSS Animations that run only once, we won't be needing the CSS shake class after it shaked the element. 但是因为shake元素只有一次运行的CSS动画,所以在它抖动元素后我们不需要CSS抖动类。

So I tried: 所以我尝试过:

$('.element').addClass('shake').removeClass('shake');

But that happens all too quickly. 但这种情况发生得太快了。

So I tried again: 所以我又试了一次:

$('.element').addClass('shake').delay(1000).removeClass('shake');

Still not play the animation and then remove the class .shake from the .element . 仍然没有播放动画,然后从.element删除.shake类。 If the user enters wrong details more then once then shake won't work. 如果用户输入错误的详细信息,那么一次摇动将无效。

You can play with the fiddle here . 你可以在这里玩小提琴。

Goal is to be able to shake the element more then once by clicking the Shake button. 目标是通过单击“摇动”按钮可以多次摇动元素。

You could use the following to remove the class when the animation completes. 您可以在动画完成时使用以下内容删除该类。

Updated Example 更新的示例

$(function () {
    $('button').click(function () {
        el = $('.element');
        el.addClass('shake');
        el.one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
        function (e) {
            el.removeClass('shake');
        });
    });
});

Just remove the shake class, add a small time out and then add the shake class. 只需删除摇动类,添加一小段时间然后添加摇动类。 That will make it shake every time: 这会让它每次都动摇:

$(function(){
$('button').click(function() {
    $('.element').removeClass('shake');
    setTimeout(function(){
          $('.element').addClass('shake');
    }, 50);
});

}); });

addClass() and removeClass() don't respect delay() , so they'll ignore the delay and just do what they were told to like the delay() doesn't exist addClass()removeClass()不尊重delay() ,所以他们会忽略延迟,只是做他们被告知的delay()不存在

fadeIn() does though. 虽然fadeIn()确实如此。

So if you do this, it should work correctly. 所以,如果你这样做,它应该正常工作。 This calls the anonymous function to remove class shake after delay and fadeIn have finished. 这称匿名函数在延迟和fadeIn完成后删除类抖动。

$('.element').addClass('shake').delay(1000).fadeIn(0, function() { $(this).removeClass('shake'); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM