Home  >  Article  >  Web Front-end  >  How to Rotate an Image on Click Using CSS and JavaScript?

How to Rotate an Image on Click Using CSS and JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 01:50:28226browse

How to Rotate an Image on Click Using CSS and JavaScript?

CSS3 Transform on Click Using Pure CSS

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn