简体   繁体   中英

Rotation on click Javascript

I want to rotate this div on click, when it's clicked it had to stay in the rotated state(45deg). but when you click again it will go back to the original rotation(0deg).

This is my code right now, maybe someone can help me!?

JSFIDDLE:

https://jsfiddle.net/sz2yfr51/2/

CODE:

    var boxopen = document.getElementById('boxopen');
boxopen.addEventListener("click", function(){
  boxopen.style.animation = "rotate 2s";
  boxopen.style.webkitAnimation = "rotate 2s";
});

You can use style.transform and style.transition:

var boxopen = document.getElementById('boxopen');
var rotate = 0;

boxopen.addEventListener("click", function(){
    rotate = rotate ? 0 : 45;
    boxopen.style.transform = "rotate(" + rotate + "deg)";
    boxopen.style.transition = "transform 2s";
});

https://jsfiddle.net/sz2yfr51/8/

All you have to do is to maintain the state using a variable and reverse the animation for that state.

Also add the animation-fill-mode : forwards; for allowing the object to settle in final keyframe state.

The following code can be used to reverse the rotation you provided.

@keyframes rotateback {
0% {
    -moz-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
    }

100% { 
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
}
}

Check out this fiddle: https://jsfiddle.net/t60Lsmqj/

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