Home > Web Front-end > CSS Tutorial > How Can I Ensure CSS3 Animations Complete on :hover Element Exit?

How Can I Ensure CSS3 Animations Complete on :hover Element Exit?

Mary-Kate Olsen
Release: 2024-12-08 00:06:12
Original
320 people have browsed it

How Can I Ensure CSS3 Animations Complete on :hover Element Exit?

Force CSS3 Animation Completion on :hover Element Exit

CSS3 animations in the :hover state provide an elegant way to add interactivity to elements. However, one limitation is that the animation aborts abruptly when the cursor leaves the element. Here's how to overcome this issue and force the animation to complete its execution, purely through CSS:

The provided animation, bounce, defines a series of keyframes that create a bouncing effect. To force the animation to continue even after the mouse exits the element, we adopt a clever technique.

  1. Add a Class Trigger:
    Create a separate class, say 'animated', with its corresponding animation (the same bounce keyframes you defined).
  2. Trigger the Animation with Hover:
    In the :hover state of the element, instead of applying the animation directly, add the animated class. This class contains the actual animation.
  3. Remove the Trigger on Animation End:
    Use JavaScript to listen for the animation end event. When the animation completes, remove the animated class from the element. This will effectively stop the animation.

Here's a modified example:

<style>
@keyframes bounce { /* Same as before */ }
.animated { animation: bounce 1s; }
</style>

<div class="box">
  Hover me!
</div>
Copy after login
$(".box").bind("webkitAnimationEnd mozAnimationEnd animationend", function(){
  $(this).removeClass("animated");  
})

$(".box").hover(function(){
  $(this).addClass("animated");        
})
Copy after login

With this approach, the animation will continue playing even after the cursor leaves the .box element. Visit this updated Fiddle for a live demonstration: http://jsfiddle.net/u7vXT/1.

The above is the detailed content of How Can I Ensure CSS3 Animations Complete on :hover Element Exit?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template