简体   繁体   中英

jQuery animations break after some time

When I stay in my div the animation won't work again if I go out and in again... So like when I stay in the field while the animation is playing when I quit and go back in it again, it doesn't start the animation over again..

HTML:

<div class="ani-bounce-slow" style="height: 200px; width: 50%; background-color: #3c3; ">
    <p> This is a bouncing Text!</p>
</div>

CSS:

.bounce-slow {
animation: bounce 3s;
}

@keyframes bounce {
    0%,
    20%,
    50%,
    80%,
    100% {
        transform: translateY(0);
    }
    40% {
        transform: translateY(-30px);
    }
    60% {
        transform: translateY(-15px);
    }
}

jQuery:

$(document).ready(function () {
$('.ani-bounce-slow').mouseenter(function () {
    $(this).addClass('bounce-slow');
});
$('.ani-bounce-slow').one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
    function (e) {
        $(this).removeClass('bounce-slow');
    }
);
});

Fiddle here

I think your problem is that you are using one() function instead of on() :

Change:

$('.ani-bounce-slow').one('webkitAnimationEnd...

To:

$('.ani-bounce-slow').on('webkitAnimationEnd...

.one( events [, data ], handler )
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

.on( events [, selector ] [, data ], handler )
Attach an event handler function for one or more events to the selected elements.

Looks like you just need to rip out the class to stop the animation on leave, and just add it back on enter. This will make the animation happen every time.

$('.ani-bounce-slow').mouseenter(function () {
    $(this).addClass('bounce-slow');
});
$('.ani-bounce-slow').mouseleave(function () {
    $(this).removeClass('bounce-slow');
});

If you want the animation to continue on mouse leave, then you need to check for animation completion, or set a timer for how loong the animation should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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