简体   繁体   中英

Issue with CSS3 transition effect

With the reference from this Rotate image with onclick , I am trying to apply a css3 transition to a div, when the div element is clicked. The demo is here Everything is working perfect.

HTML

<div class="testRotate">Test rotate</div>

CSS

.testRotate{
 width: 300px;
  height: 50px;
  border: 1px solid black;
  padding: 20px;
  margin: 0px auto;
  margin-top: 50px;
  -moz-transition: transform 1s;
  -webkit-transition: transform 1s;
  transition: transform 1s;
}

.testRotate.rotate{
  transform: rotate(360deg);
  -moz-transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
}

JS

$(function(){
    $("div").click( function(){
        $(this).addClass("rotate");
        setTimeout(function(){$("div").removeClass("rotate");}, 1500);
    });
});

In this example, when onclicking the div, rotate class will be applied to it, so it will rotate for 360 degree, as defined in css. After sometimes we are removing the rotate class, so again the div is rotating back to its original position.

Now what i need is, when it clicked the element is has to rotate for 360 degree, but it should not suppose to rotate back once the rotate class got removed from it.

You can add a new class for transition and remove rotate as well as the class for transition.

  $(function(){ $("div").click( function(){ $(this).addClass("testRotate rotate"); setTimeout(function(){$("div").removeClass("testRotate rotate");}, 1500); }); }); 
  .test { width: 300px; height: 50px; border: 1px solid black; padding: 20px; margin: 0px auto; margin-top: 50px; } .testRotate{ -moz-transition: transform 1s; -webkit-transition: transform 1s; transition: transform 1s; } .testRotate.rotate{ transform: rotate(360deg); -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test testRotate">Test rotate</div> 

Fiddle Demo

Fiddle

$("div").click(function() {
    if (  $(this).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(360deg)");
    } else {
        $(this).css("transform","");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM