【问题标题】:Rotate div-element with every click on a button [duplicate]每次单击按钮时旋转 div 元素 [重复]
【发布时间】:2019-09-11 12:52:58
【问题描述】:

要点:点击按钮时,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>

【问题讨论】:

  • jQuery dupe 很容易翻译成你可以使用的东西:var r = 0; $('#icon').click(function(){ $(this).css('transform','rotate(' + (r += 360) + 'deg)'); });

标签: javascript css


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2016-07-21
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多