切换CSS类的纯Javascript替代方案?

Guy*_*Guy 3 html javascript css

我的目标是在每次点击时将div旋转180度,而不会切换CSS类。

第一次单击可以实现一个旋转(.style.transform =“ rotate(180deg)”;),但是任何后续单击都无效。

顺便说一句,那到底是为什么?div的ID并未更改,因此从理论上讲,相同的触发器(在这种情况下为单击)应该调用相同的函数,对吗?但事实并非如此。我不知道这里的逻辑是什么,技术上的解释是什么,并且在实践中,如何再次操作该后div(即在其JavaScript操作之后的原始div),而又无需切换CSS类。

function rotate() {
    document.getElementById("container").style.transform = 
    "rotate(180deg)";
}
Run Code Online (Sandbox Code Playgroud)
.container {
    width: 200px;
    height: 400px;
    border: 5px solid;
    border-bottom-color: blue;
    border-top-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container" id="container" onclick="rotate()"></div>

    
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 5

The first time you change the transformation from "" to "rotate(180deg)", so it rotates.

Subsequent times you change it from "rotate(180deg)" to "rotate(180deg)" … which isn't a change at all, so nothing happens.

If you want to change it, then you need to actually assign a different value to it.

e.g.

const style = document.getElementById("container").style;
if (style.transform) {
    style.transform = "";
} else {
    style.transform = "rotate(180deg)";
}
Run Code Online (Sandbox Code Playgroud)

切换课程更加简单明了。

const style = document.getElementById("container").style;
if (style.transform) {
    style.transform = "";
} else {
    style.transform = "rotate(180deg)";
}
Run Code Online (Sandbox Code Playgroud)
document.querySelector("#container").addEventListener("click", e => e.currentTarget.classList.toggle("rotated"));
Run Code Online (Sandbox Code Playgroud)
.container {
  width: 200px;
  height: 400px;
  border: 5px solid;
  border-bottom-color: blue;
  border-top-color: red;
  transition: transform 0.25s;
}

.rotated {
  transform: rotate(180deg);
}
Run Code Online (Sandbox Code Playgroud)