每次单击按钮即可旋转div元素

Tan*_*ane 2 javascript css

要点:单击按钮时,content-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)';
});
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="content">
  <p>It's spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>
Run Code Online (Sandbox Code Playgroud)

小智 5

您只需要继续添加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;
});
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="content">
  <p>Its spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>
Run Code Online (Sandbox Code Playgroud)