使用CSS在单击事件上单独为每个转换属性设置动画

时间:2018-06-18 19:38:55

标签: javascript css css3 css-transitions css-transforms

  

我希望每当我点击div时,首先是translate,然后是rotate,最后是scale。此外,当我再次点击时,我想以同样的方式reverse it back

我有以下代码:

$(() => {
  $('div').on('click', () => {
    $('div').toggleClass('clicked');
  });
});
div.normal {
  height: 20px;
  width: 100px;
  background: black;
  transition: 2s all;
}
div.clicked {
  transform: translate(100px, 100px) rotate(45deg) scale(2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='normal'></div>

如您所见,所有转换都在同一时间发生。但是,我希望它们分开发生。我如何实现这一目标?

提前致谢!

2 个答案:

答案 0 :(得分:6)

使用关键帧分解动画。以下是代码的最低版本:

&#13;
&#13;
var $el = $('#to-animate')
var firstClick = true

$el.click(() => {
  $el.toggleClass('clicked')

  if (!firstClick) {
    $el.toggleClass('unclicked')
  }
  
  firstClick = false
})
&#13;
div.normal {
  height: 20px;
  width: 100px;
  background: black;
}
div.clicked {
  animation: transforms 2s forwards;
}
div.unclicked {
  animation: transforms-2 2s reverse;
}

@keyframes transforms {
  33% {
    transform: translate(100px, 100px);
  }
  66% {
    transform: translate(100px, 100px) rotate(45deg);
  }
  100% {
   transform: translate(100px, 100px) rotate(45deg) scale(2);
  }
}

@keyframes transforms-2 {
  33% {
    transform: translate(100px, 100px);
  }
  66% {
    transform: translate(100px, 100px) rotate(45deg);
  }
  100% {
   transform: translate(100px, 100px) rotate(45deg) scale(2);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="to-animate" class='normal'></div>
&#13;
&#13;
&#13;

更新

修改以包含反转动画的功能(使代码编辑更少)

答案 1 :(得分:1)

一个想法是依靠其他属性来实现相同的效果,并能够应用不同的过渡

&#13;
&#13;
$(() => {
  $('div').on('click', () => {
    $('div').toggleClass('clicked');
  });
});
&#13;
div.normal {
  height: calc(20px * var(--s,1));
  width: calc(100px * var(--s,1));
  background: black;
  position:relative;
  top:0;
  left:0;
  transition: 2s top 4s,2s left 4s,2s width 2s,2s height 2s,2s transform;
}
div.clicked {
  top:100px;
  left:100px;
  --s:2;
  transform:rotate(45deg);
  transition: 2s top,2s left,2s width 2s,2s height 2s,2s transform 4s;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='normal'></div>
&#13;
&#13;
&#13;