当我点击两次css3转换不起作用

时间:2016-07-07 06:43:48

标签: javascript css3 transform

当我点击开始按钮时,我想要方形旋转。但是:

当我点击一次时,它正在工作。当我跑两次时,这个css3效果不起作用。

$(function(){
						
	var $obj=$(".red");
	
	$("#btnStart").on("click",function(){
		$obj.removeClass("run").addClass("run");
	});
			
});
body{padding:100px;}

.red{background:#f00;width:100px;height: 100px;}

.run{
	transform:rotate(3600deg);
	transition: transform 5s ease 0s;
	-moz-transition:transform 5s ease 0s;
	-webkit-transition:transform 5s ease 0s;
	-o-transition:transform 5s ease 0s;
}
<html>
	<head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	</head>
<body>
	<div class="red"></div>
	
	<br/>
	
	<button id="btnStart">
		开始旋转
	</button>
	
	</body>
</html>

2 个答案:

答案 0 :(得分:2)

删除和添加类之间需要超时。否则它将无法识别更改。

$(function(){
  var $obj=$(".red");
  $("#btnStart").on("click",function(){
    $obj.removeClass("run");
    setTimeout(function(){
      $obj.addClass("run");
    }, 10);
  });		
});
body{padding:100px;}

.red{background:#f00;width:100px;height: 100px;}

.run{
	transform:rotate(3600deg);
	transition: transform 5s ease 0s;
	-moz-transition:transform 5s ease 0s;
	-webkit-transition:transform 5s ease 0s;
	-o-transition:transform 5s ease 0s;
}
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="red"></div><br/>
    <button id="btnStart">
		开始旋转
	</button>
  </body>
</html>

答案 1 :(得分:1)

您可以使用jQuery的animate()函数,而不是添加/删除类!

$(function(){
						
	var $obj=$(".red");
	
	$("#btnStart").click(function(){
		$('.red').animate({  borderSpacing: -3600 }, {
                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:'slow'
           },'linear');
	});
			
});
body{padding:100px;}

.red{background:#f00;width:100px;height: 100px;}
<html>
	<head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	</head>
<body>
	<div class="red"></div>
	
	<br/>
	
	<button id="btnStart">
		开始旋转
	</button>
	
	</body>
</html>