Re-triggering WebKit CSS Animations with JavaScript
In CSS, animations are time-limited sequences that can be applied to elements using the @-webkit-keyframes rule. However, in some cases, it may be necessary to re-trigger an animation without using timeouts or multiple animations.
One solution lies in utilizing the animationEnd event, which is fired when an animation completes. In WebKit browsers, this event is known as webkitAnimationEnd. By attaching an event listener to the element, it becomes possible to reset the animation once it has finished.
Event-driven Reset
In vanilla JavaScript:
var element = document.getElementById('box'); element.addEventListener('webkitAnimationEnd', function(){ this.style.webkitAnimationName = ''; }, false); document.getElementById('button').onclick = function(){ element.style.webkitAnimationName = 'shake'; };
In jQuery:
var $element = $('#box').bind('webkitAnimationEnd', function(){ this.style.webkitAnimationName = ''; }); $('#button').click(function(){ $element.css('webkitAnimationName', 'shake'); });
Cross-Browser Compatibility
For cross-browser support, a library like CSS3 transition tests can be utilized. It provides a support object that detects various CSS properties and events, including animation support:
var css3AnimationSupport = (function(){ var div = document.createElement('div'), divStyle = div.style, support = { transition: ... transform: ... animation: ... }; }());
By using this support object, it is possible to detect the animation property and event for each browser, allowing for consistent handling of CSS animations across multiple platforms.
The above is the detailed content of How Can I Re-trigger WebKit CSS Animations with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!