How to Re-trigger a WebKit CSS Animation via JavaScript
This question addresses the issue of re-triggering a CSS animation using JavaScript. The existing animation rule "@-webkit-keyframes shake" defines a shaking effect, but subsequent attempts to activate it again via JavaScript prove unsuccessful.
The solution provided leverages the "animationEnd" event, specifically "webkitAnimationEnd" for WebKit browsers. When this event is triggered, it indicates the completion of the animation.
To re-trigger the animation, an event listener is added to the element for the "webkitAnimationEnd" event. Upon receiving this event, the element's "webkitAnimationName" style property is cleared, effectively resetting the animation.
Example (Plain Vanilla JavaScript):
var element = document.getElementById('box'); element.addEventListener('webkitAnimationEnd', function(){ this.style.webkitAnimationName = ''; }, false); document.getElementById('button').onclick = function(){ element.style.webkitAnimationName = 'shake'; // You may want to prevent default action here. };
Example (jQuery):
var $element = $('#box').bind('webkitAnimationEnd', function(){ this.style.webkitAnimationName = ''; }); $('#button').click(function(){ $element.css('webkitAnimationName', 'shake'); // You may want to prevent default action here. });
Cross-Browser Support:
For cross-browser support, the "css3AnimationSupport" object can be used to detect CSS transition, transform, and animation properties supported by different browsers.
var css3AnimationSupport = (function(){ var div = document.createElement('div'), divStyle = div.style; return { transition: (function(){ return divStyle.MozTransition === ''? {name: 'MozTransition' , end: 'transitionend'} : (divStyle.MsTransition === ''? {name: 'MsTransition' , end: 'msTransitionend'} : (divStyle.WebkitTransition === ''? {name: 'WebkitTransition', end: 'webkitTransitionEnd'} : (divStyle.OTransition === ''? {name: 'OTransition' , end: 'oTransitionEnd'} : (divStyle.transition === ''? {name: 'transition' , end: 'transitionend'} : false)))); })() // ... Other detections omitted for brevity }; }());
The above is the detailed content of How to Restart a WebKit CSS Animation Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!