Continuous rotation on hover exit

风流意气都作罢 提交于 2019-12-11 04:50:00

问题


Consider the following fiddle: http://jsfiddle.net/a7EVf/5/

Is it possible to have the div rotate through (effectively to 360 degrees instead of 0) on hover out instead of moving back counterclockwise?

I would rather NOT use JavaScript (including jQuery) if possible - I realize it would be simple enough to set

transform: rotate(360deg); /*also the vendor-specific versions*/

on the original using JS (and once it reaches 360 reset it to 0 without a transition), but is it possible to do this only using CSS3?


回答1:


Using CSS3 animation, we can make the block rotate from 0 to 180 degree on hover and then rotate from 180 to 360 degree when not hovered.

#block {
  position: absolute;
  width: 100px;
  height: 50px;
  left: 100px;
  top: 100px;
  background: black;
  color: white;
  animation-name: out;  /* animation to rotate on hover out*/
  animation-duration: 1s;  /* duration for the animation, increase it to slow it down*/
}
#block:hover {
  animation-name: in;  /* animation to rotate on hover */
  animation-duration: 1s;
}
@keyframes in {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(180deg);
  }
}
@keyframes out {
  from {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<div id="block"></div>

Note:

  1. This causes the block to rotate on page load also. There is no solution for this other than using JS and nullify the effect on page load.
  2. As you mentioned, there is a bit of snapping when we hover in and out at very quick intervals. This can be explained by having a look at the answers here and here. Once the animation is no longer applicable (that is, the selector is no longer applicable), the animation will abruptly stop and return back to its original un-transformed position.


来源:https://stackoverflow.com/questions/19251804/continuous-rotation-on-hover-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!