简体   繁体   中英

CSS transform rotate in the same direction each time

I'm wanting to make an element on a web page rotate 360 degrees anticlockwise each time a button is clicked. I've found some example code showing how to do this but the only issue is that currently it rotates in alternating directions.

Is there a simple way to ensure that the element rotates in the same direction every time?

Here's the example code: http://codepen.io/impressivewebs/pen/niurC

.

Cheers

Your example adds and removes the class that applies the transformation, which has the effect of applying the transformation when the class is added, and then undoing it when the class is removed, hence the reversal of the rotation on the second click.

To increment the rotation each time, you could use JavaScript to keep count of the current rotation value and increment it when the button is clicked, I've forked your example on CodePen here: http://codepen.io/anon/pen/aObMYK to illustrate. Note that I've changed the increment to 30 degrees so you can see what's going on more clearly. If you want to have it as 360 degree rotation each time, just change the value set in counter += 30; to 360.

The trick is to increase your rotation instead of reserting it. In the following code we will keep increasing the rotation by 360, this will make it rotate in one direction on every click.

I only changed your javascript function to achieve this:

var angle =0;
$('button').click(function () {
   angle += 360;
  $(".box").css({'transform': 'rotate(' + angle + 'deg)'});

});

Full Code

 var angle =0; $('button').click(function () { //$('.box').toggleClass('box-rotate'); angle += 360; $(".box").css({'transform': 'rotate(' + angle + 'deg)'}); }); 
 .box { background: lightblue; width: 100px; height: 100px; margin: 20px auto; transition: transform 1s linear; transform-origin: top left; transform-style: preserve-3D; } .box-rotate { transform: rotate(360deg); } button { display: block; margin: auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div class="box"></div> <button>click me</button> 

You're using toggleClass in your JS script. Toggle method is used to switch between two values. When you use toggleClass on that element you're adding and removing box-rotate class on every button click. To repeat a function on dom, you'll need javascript and in that case your code will look like

var counter = 0;

$('button').click(function () {
    var box = $('.box');
  // box.toggleClass('box-rotate');
    counter += 360;
  $('.box').css('transform', 'rotate(' + counter + 'deg)')
});

Here is the working code .

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