Home >Web Front-end >CSS Tutorial >How can I Rotate an Image on Click using CSS3 Transform?
In an effort to enhance user interaction, you may encounter the need to transform an element upon click using CSS3. Specifically, rotating an image to create a cross symbol is a common task. While hovering is a common trigger for transformation, this article explores the possibility of using the onClick event exclusively through CSS.
Initially, the provided code utilizes the hover event to rotate the image by 45 degrees. However, to trigger the transformation on click, a modification is required.
CSS offers the :active pseudo-class which is designed to style elements when they are being clicked. By leveraging this pseudo-class, you can achieve the desired behavior:
<code class="css">.crossRotate:active { transform: rotate(45deg); -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); }</code>
This code will rotate the image 45 degrees when it is clicked. However, it's important to note that the transformation will vanish once the click is released. This is because the :active state is only active during the click itself.
If you want the transformation to persist after the click, you'll need to employ JavaScript. By capturing the click event using jQuery, you can toggle the transformation using the css() method:
<code class="javascript">$( ".crossRotate" ).click(function() { if ( $( this ).css( "transform" ) == 'none' ){ $(this).css("transform","rotate(45deg)"); } else { $(this).css("transform","" ); } });</code>
In this code, the transform property is checked. If it's set to none, the transformation is applied, otherwise it is removed. This allows you to toggle the cross symbol on and off with each click.
By utilizing these techniques, you can effectively rotate an image using CSS3 transform on click, both with and without JavaScript to maintain the transformation beyond the click event.
The above is the detailed content of How can I Rotate an Image on Click using CSS3 Transform?. For more information, please follow other related articles on the PHP Chinese website!