CSS 动画,点击时切换旋转

CSS animation, toggle rotate on click

我尝试让插入符号在点击我的下拉菜单时旋转 180 度。在我尝试实施的解决方案中,它将插入符号的 class 更改为点击时向上切换或向下切换。我第一次点击它向上旋转,第二次它立即回到它的起始位置然后向上旋转。我闻到了肮脏的代码,添加此切换旋转动画的最简单方法是什么。在此先感谢您的帮助。
这是我目前的 css:

.toggle-up {
  animation-name: toggle-up;
  animation-delay: 0.25s;
  animation-duration: 0.75s;
  animation-fill-mode: forwards;
}
.toggle-down {
  animation-name: toggle-down;
  animation-delay: 0.25s;
  animation-duration: 0.75s;
  animation-fill-mode: forwards;
}

/*animations*/
@keyframes toggle-up {
  100% {
    transform: rotate(180deg);
  }
}
@keyframes toggle-down {
  100% {
    transform: rotate(180deg);
  }
}

对于这么简单的事情,您真的不需要关键帧动画。如果您只是在单击时向图标添加 class 然后将其删除,这将应用您的旋转。 Here is a working plunkr using font awesome and a simple rotation。这只是一个简单的示例,您需要使用供应商前缀并注意 css 转换在旧浏览器中不起作用。

<div id="container">
    <i id="icon" class="fa fa-arrow-down"></i>
</div>

.fa-arrow-down{
  transform: rotate(0deg);
  transition: transform 1s linear;
}

.fa-arrow-down.open{
  transform: rotate(180deg);
  transition: transform 1s linear;
}

(function(document){
  var div = document.getElementById('container');
  var icon = document.getElementById('icon');
  var open = false;

  div.addEventListener('click', function(){
    if(open){
      icon.className = 'fa fa-arrow-down';  
    } else{
      icon.className = 'fa fa-arrow-down open';
    }

    open = !open;
  });
})(document);
.square {
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  transition: all 0.75s 0.25s;
}

.toggle-up {
  transform: rotate(180deg);
}

.toggle-down {
  transform: rotate(0);
}

您应该有一个初始状态才能完成动画。

示例如下:codepen

更新

这里是不使用 javascript 的版本:codepen

<label for="checkbox">
  <input type="checkbox" id="checkbox">
  <div class="square toggle-down"></div>
</label>


#checkbox {
  display: none;
}

.square {
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  transition: all 0.75s 0.25s;
  transform: rotate(0);
}

#checkbox:checked + .square {
  transform: rotate(180deg);
}

总体思路是使用 Adjacent sibling selectors 和复选框 checked 状态更改块 class。