Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-01 01:50:28
Original
347 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template