CSS3 Animate Image on Click Using Pure CSS
In this article, we'll explore how to rotate an image 45 degrees on click using pure CSS, without relying on JavaScript.
Initial Code
You have provided the following CSS:
<code class="css">img { display: block; margin: 20px; } .crossRotate { -webkit-transition-duration: 1s; -moz-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; -webkit-transition-property: -webkit-transform; -moz-transition-property: -moz-transform; -o-transition-property: -o-transform; transition-property: transform; } .crossRotate:hover { -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); }</code>
This code currently animates the rotation on hover, but it does not respond to clicks.
CSS-Only Solution
To achieve the rotation on click using pure CSS, you can utilize the :active selector. Here's how your corrected CSS should look:
<code class="css">.crossRotate { -webkit-transition-duration: 1s; -moz-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; -webkit-transition-property: -webkit-transform; -moz-transition-property: -moz-transform; -o-transition-property: -o-transform; transition-property: transform; } .crossRotate:active { -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); }</code>
Now, when you click the image, it will rotate 45 degrees. However, it will remain rotated after releasing the click. If you want the image to return to its original state after each click, you'll need to use JavaScript.
JavaScript Solution
Using JavaScript, you can toggle the rotation on click as follows:
<code class="javascript">$( ".crossRotate" ).click(function() { if ( $( this ).css( "transform" ) == 'none' ){ $(this).css("transform","rotate(45deg)"); } else { $(this).css("transform","" ); } });</code>
This code checks the current transformation of the image. If it's "none," it means the image is not rotated, so it rotates it by 45 degrees. If it's not "none," it resets the transformation, returning the image to its original state.
The above is the detailed content of How can I rotate an image 45 degrees on click using only CSS?. For more information, please follow other related articles on the PHP Chinese website!