Home > Article > Web Front-end > How to Rotate an Image on Click Using CSS and JavaScript?
To achieve image rotation on click using pure CSS, we've encountered a challenge where our existing code rotates on hover. Let's focus on a pure CSS solution.
Solution:
CSS only:
<code class="css">.crossRotate:active { transform: rotate(45deg); -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); }</code>
This solution utilizes the :active pseudo-class, which triggers the rotation upon clicking the image. However, the transform will not persist after the click.
For a persistent transform, we'll need to introduce JavaScript:
<code class="javascript">$( ".crossRotate" ).click(function() { if ( $( this ).css( "transform" ) == 'none' ){ $(this).css("transform","rotate(45deg)"); } else { $(this).css("transform","" ); } });</code>
This jQuery code toggles the transform based on the current value. If the transform is 'none', it applies the 45-degree rotation; otherwise, it removes the transform.
The above is the detailed content of How to Rotate an Image on Click Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!