【问题标题】:CSS animation, toggle rotate on clickCSS动画,点击时切换旋转
【发布时间】:2015-09-15 12:14:48
【问题描述】:

我尝试让下面的插入符号在单击下拉菜单时旋转 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);
  }
}

【问题讨论】:

  • 你的意思是第一次向上旋转后的状态没有保留,当你再次点击它时,它再次执行向上旋转?如果是,我认为您应该使用 javascript 来保留最后一个动画的状态

标签: javascript html css css-animations


【解决方案1】:
.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状态来改变block类。

【讨论】:

  • 我明白了,谢谢,我正试图弄清楚如何使用过渡。您的代码笔中的 javascript if 语句中的 tilda 运算符的目的是什么?
  • 哦,对不起。我正在尝试在不使用 JS 的情况下编写此代码。这是草稿。我会把它带到初始状态。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多