2016-03-02 33 views
0

只是爲了先點擊img類旋轉180deg和後級的表演,但我要爲第二次點擊,如果旋轉180deg變化0deg再次和後班級表演。只是爲了先點擊「IMG」級旋轉工作,但不能再點擊

發佈課程顯示正在工作,但只是爲了第一次點擊工作而旋轉。

<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script> 
$(document).ready(function() { 
    $(".op-cl").click(function() { 
     $(".post").toggle("slow", function() { 

      if ($('.img').css('transform', 'rotate(0deg)')) { 
       $('.img').css('transform', 'rotate(180deg)'); 
      } else if ($('.img').css('transform', 'rotate(180deg)')) { 
       $('.img').css('transform', 'rotate(0deg)'); 
      } 

     }); 
    }); 
}); 
+0

請添加jsfiddle – brk

回答

0

$('.img').css('transform', 'rotate(0deg)')將始終爲真,因爲它返回了jQuery鏈的$(".img")。它設置變換屬性並不計算。請參閱http://api.jquery.com/css/以供參考。

爲了解決這個問題,你可以添加一個類來檢查它是否已經旋轉:

$(document).ready(function() { 
    $(".op-cl").click(function() { 
     $(".post").toggle("slow", function() { 
      if ($('.img').hasClass('rotated')) { 
       $('.img').css('transform', 'rotate(0)'); 
       $('.img').removeClass('rotated') 
      } else { 
       $('.img').css('transform', 'rotate(180deg)'); 
       $('.img').addClass('rotated'); 
      } 
     }); 
    }); 
}); 
0
<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script> 
    $(document).ready(function() { 
     $(".op-cl").click(function() { 
      var click=1; 
      $(".post").toggle("slow", function() { 

       if (click % 2 !=0) { 
        $('.img').css('transform', 'rotate(180deg)'); 
       } else if (click % 2 ==0) { 
        $('.img').css('transform', 'rotate(0deg)'); 
       } 
       click++; 
      }); 
     }); 
    }); 
0

IMO更好地使用toggle當你想兩個值之間切換:

$(document).ready(function(){ 
 
    $(".op-cl").click(function() { 
 
     $('.img').toggle(function() { 
 
      $("#user_button").css({transform: "rotate(0deg)"}); 
 
     }, function() { 
 
      $("#user_button").css({transform: "rotate(180deg)"}); 
 
     }); 
 
    }); 
 
});
img{ 
 
    width:200px; 
 
    height:200px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class='op-cl'>op-cl</button> 
 
<br> 
 
<img class='img' src='https://pbs.twimg.com/profile_images/604644048/sign051.gif' style='transform:rotate(0deg)'/>