每次单击按钮时旋转div元素

7

简而言之:当单击按钮时,内容div会旋转360度。 但是,在第二次单击时,没有任何反应。

我的要求是:每次点击按钮时,div元素都会像第一次点击时一样旋转360度

我已经找到了一些jQuery建议,但我希望通过使用JavaScript来完成此操作。

var content = document.getElementById("content");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
  content.style = 'transform: rotate(' + 0 + '360deg)';
});
#content {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 1s ease-in-out;
}

#btn {
  width: 100px;
  height: 50px;
  background: grey;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
}

a {
  color: white;
  text-decoration: none;
}
<div id="content">
  <p>It's spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>


jQuery的代码非常容易转换成你可以使用的形式:var r = 0; $('#icon').click(function(){ $(this).css('transform','rotate(' + (r += 360) + 'deg)'); }); - mplungjan
1个回答

9

您只需要不断添加360!


var content = document.getElementById("content");
var btn = document.getElementById("btn");
var rot = 360;
btn.addEventListener("click", function() {
  content.style = 'transform: rotate(' + rot + 'deg)';
  rot += 360;
});
#content {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 1s ease-in-out;
}

#btn {
  width: 100px;
  height: 50px;
  background: grey;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
}

a {
  color: white;
  text-decoration: none;
}
<div id="content">
  <p>Its spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接