jQuery rotate div onclick +/-90

2020-07-24 16:10发布

问题:

I was wondering if there is an easy way to rotate a div +90 degrees after clicking it and by clicking it next time it returns to 0 degrees (so that the div rotates -90 degrees). Since I couldn't find anything I was looking for your help. Thanks.

回答1:

You could use toggleClass and apply css transform to that class:

$('#rotate').click(function(){
    $(this).toggleClass('rotated');
});

fiddle

.rotated { 
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}


回答2:

You need to use CSS for rotating the div. And for +-90 you have to add/remove to the div, this can be easy achieved with toggleClass. Adding this behaviour inside a click event will result something like below.

$('.square').click(function() {
    $(this).toggleClass('rotate-90');
});
.square {
  width: 150px;
  height: 100px;
  background-color: red;
}

.rotate-90 { 
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square">
  
</div>