Home > Web Front-end > CSS Tutorial > How Can I Prevent CSS3 Hover Animations from Stopping Prematurely on Mouse Exit?

How Can I Prevent CSS3 Hover Animations from Stopping Prematurely on Mouse Exit?

DDD
Release: 2024-12-07 10:44:12
Original
354 people have browsed it

How Can I Prevent CSS3 Hover Animations from Stopping Prematurely on Mouse Exit?

Preserving CSS3 Animations Triggered by :hover on Mouse Exit

When employing CSS3 animations on an element's :hover state, it's common to encounter the issue of sudden animation termination when the mouse cursor leaves the element. This behavior can be undesirable if you wish the animation to complete its natural duration regardless of mouse presence.

Solution: Incorporating JavaScript

Unfortunately, there is no standardized CSS solution for this requirement. To overcome this limitation, you can incorporate a bit of JavaScript as follows:

  1. Assign an animation class: Add an animation class to the element that includes the desired animation.
  2. Handle animation end event: Attach an event listener to the animation end event, which is supported by various browsers.
  3. Remove animation class: Within the event listener, remove the animation class from the element, allowing the animation to complete its execution.
  4. Trigger animation on hover: Modify the hover handler to add the animation class to the element when it's hovered over.

Example:

$(".box").bind("webkitAnimationEnd mozAnimationEnd animationend", function(){
  $(this).removeClass("animated");
})

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

This code attaches an event listener to the animation end event and removes the "animated" class from the element upon its completion. Additionally, it adds the same animation class when the element is hovered over.

The above is the detailed content of How Can I Prevent CSS3 Hover Animations from Stopping Prematurely on Mouse 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template