Rotate image with onclick

2019-01-19 09:17发布

问题:

I try to make a toggle button where my image (an arrow) will be rotated by 180 degrees each click:

<a href='#' onclick='$(\"#divToggle\").slideToggle(\"slow\");'>
<img src='blue_down_arrow.png' onclick='$(this).rotate(180);' /></a>

<div id='divToggle' style='display:none;'>...CONTENT...</div>";

This code toggle my div but the image rotates only for the first click and then stays "up". I am using this : http://code.google.com/p/jqueryrotate/

回答1:

This is because the value for rotate angle is absolute, not based on the last rotate.

Working code:

jQuery

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}

HTML

<img src='blue_down_arrow.png' onclick='rotateMe(this);' /></a>

Update: Shorter code

var rotate_angle = 0;

<img src='blue_down_arrow.png' onclick='rotate_angle = (rotate_angle + 180) % 360; $(this).rotate(rotate_angle);' /></a>


回答2:

Click to see CSS3 transition demo

check out this demo. It uses CSS3 for transition + transform rotating

.testRotate{
  -moz-transition: transform 1s;
  -webkit-transition: transform 1s;
  transition: transform 1s;
}

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

these are vital part of this demo =)



回答3:

You may write like this. demo

jQuery(document).ready(function(){
   var deg_temp =45;
  jQuery("#image1").click(function(){
     deg_temp = deg_temp+30;
  jQuery(this).rotate(deg_temp);
  })

});


回答4:

try this:

$('img').click(function(){
$('img').rotate({ angle: 0, bind:{
    "click":function(){
      $(this).rotate({animateTo:360});
    }
  }
 });
});


回答5:

Use CSS3 for the rotation:

  1. In Mozilla Firefox this will be -moz-transform: rotate(180deg)
  2. In Webkit based browsers, i.e. Chrome: -webkit-transform: rotate(180deg)
  3. In Opera: -o-transform: rotate(180deg)
  4. In IE: -ms-transform: rotate(180deg) (only IE9)
  5. In pre-IE9: not easily possible, will need the use of Matrix Filter

Use jQuery rotate plugin to unify all the browser differences.



回答6:

This will enable you to perform an additional rotation of each clik

var degrees = 0;
  $('.img').click(function rotateMe(e) {

    degrees += 90;

    //$('.img').addClass('rotated'); // for one time rotation

    $('.img').css({

      'transform': 'rotate(' + degrees + 'deg)',
      '-ms-transform': 'rotate(' + degrees + 'deg)',
      '-moz-transform': 'rotate(' + degrees + 'deg)',
      '-webkit-transform': 'rotate(' + degrees + 'deg)',
      '-o-transform': 'rotate(' + degrees + 'deg)'
    });

https://jsfiddle.net/Lnckq5om/1/