jQuery - how to “reset” a .css() rotated icon?

℡╲_俬逩灬. 提交于 2020-01-04 19:19:11

问题


I have an icon, which is rotated on click.

I'd like to "reset" it (without a page refresh), so it would rotate on every click.

$('#icon').click(function(){
    $(this).css('transform','rotate(360deg)');
});

Here is the example: http://jsfiddle.net/tDvD9/1/

Thanks!


回答1:


Here's one simple way:

var r = 0;
$('#icon').click(function(){
    $(this).css('transform','rotate(' + (r += 360) + 'deg)');
});

That way your "transform" property will change on each click (until somebody clicks 100 million times or so).




回答2:


This is not a very elegant solution (I think the worst part is that you have to know the transition time in the JS) but you can reset it with setTimeout. The inner setTimeout is necessary or else it will take 3 seconds to rotate back to 0.

$(this).css('transform','rotate(360deg)');
setTimeout(function () {
    this.css({'transform': 'rotate(0deg)', 'transition': '0'});
    setTimeout(function () {
        this.css('transition', 'all 3s ease-in-out');
    }.bind(this), 10);
}.bind($(this)), 3000);

The inner setTimeout is done to

http://jsfiddle.net/ExplosionPIlls/tDvD9/2/




回答3:


I reset it by rotate it back

var last=0; // rotated degree last time set to 0
var x=360;  //degree to rotate
var t=9000;  // time duration
$("#item").click(function(){ //click
  rotateme(x);// call function
});
function rotateme(x){
 if(last!=0){// if last has value
   // rotate it back
   $("#id").animate({  borderSpacing: -last }, {
       duration:0
   });
 }
 // rotate setting x,y position
 $("#id").css("transform-origin",0% 0%);
 $("#id").css("-ms-transform-origin",0% 0%);
 $("#id").css("-webkit-transform-origin",0% 0%);
 $("#id").css("-moz-transform-origin",0% 0%);
 // rotate steps
 $("#id").animate({  borderSpacing: x }, {
    step: function(now,fx) {    
    $(this).css('-webkit-transform','rotate('+now+'deg)'); 
    $(this).css('-moz-transform','rotate('+now+'deg)');
    $(this).css('transform','rotate('+now+'deg)');
    },
    duration:t
 });
 last=x;
} 


来源:https://stackoverflow.com/questions/17503359/jquery-how-to-reset-a-css-rotated-icon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!