CSS动画,点击时切换旋转

时间:2015-06-29 06:05:18

标签: javascript html css css-animations

我尝试让插入符号在下面旋转180度点击我的下拉菜单。在我试图实现的解决方案中,它将插入符号的类更改为切换或在单击时切换。我第一次点击它会向上旋转,第二次它立即返回到它的起始位置然后再向上旋转。我闻到了脏代码,最简单的方法是添加这个切换旋转动画。在此先感谢您的帮助。
继续我现在的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);
  }
}

enter image description here

2 个答案:

答案 0 :(得分:19)

对于这么简单的事情,你真的不需要关键帧动画。如果您只是在点击时向您的图标添加一个类,然后将其删除,这将应用您的轮换。 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);

答案 1 :(得分:7)

.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和复选框选中状态来更改块类。

相关问题