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

标签 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)';
});
#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>

最佳答案

你只需要继续添加 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>

关于javascript - 每次单击按钮时旋转 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889652/

相关文章:

javascript - 映射并返回被视为对象的 JSX

javascript - Chrome 使用了 JSHeapSize 属性

javascript - 表单提交上的 CSS/JQuery/Angular 转换

html - 如何在 css 中仅针对非触摸设备设置样式?

css - 如何使用 JSS 设置没有类的输入标签的样式

javascript - 如果 hasClass 帮助和从变量中减去

javascript - 为什么 .html() 和 .text() 只选择第一个词?

支持流体布局的 CSS 框架

css - 使用 em 时,Firebug 可以显示字体大小继承树吗?

css - 字体在 ie 中的 times new roman 中被卡住