简体   繁体   English

悬停时加速图像旋转

[英]Accelerate image spinning on hover

I got an image 我有一张图片

<div class="spin-image">
    <img src="images/color-wheel.png" alt="" />
</div>

and its corresponding css 及其对应的CSS

.spin-image {
  -webkit-animation:spin 10s linear infinite;
  -moz-animation:spin 10s linear infinite;
  animation:spin 10s linear infinite;

  -webkit-transition-duration: 2s; /* Safari */
  transition-duration: 2s;
}

.spin-image:hover {
  -webkit-animation:spin 2s linear infinite;
  -moz-animation:spin 2s linear infinite;
  animation:spin 2s linear infinite;
}

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

What I'm trying to do is to accelerate the image spinning on hover. 我正在尝试做的是加速悬停时的图像旋转。 The animation works, but the transition does not. 动画有效,但过渡无效。

If you realise, this is like the animation and the hover animation are two different ones, and they reset to their virtual state of rotation in case they were running all the time you were or weren't hovering. 如果您意识到的话,就好像动画和悬停动画是两个不同的动画一样,它们会重置为虚拟的旋转状态,以防它们一直在您悬停或不在悬停时一直在运行。 Unfortunatly, it is not posible to animate the transition between 2 different animation-durations. 不幸的是,无法为两个不同动画持续时间之间的过渡设置动画。

Yet if you really really need a solution for this, you could program the animation using transition and a javascript interval that resets the positions for every turn. 但是,如果您确实确实需要解决方案,则可以使用过渡和JavaScript间隔对动画进行编程,以每转一圈重置位置。 This way yo can reset the property and the duration of the transition at any time with javascript. 这样,您可以随时使用javascript重置属性和过渡持续时间。

I made you a pen: http://codepen.io/vandervals/pen/aONmVL 我给你一支笔: http : //codepen.io/vandervals/pen/aONmVL

This is the css you need: 这是您需要的CSS:

.spin-image img{
  transition: transform 2s linear;
  transform: rotate(0deg);
}
.spin-image img.hover{
  transition: transform 1s linear;
}

And the JS: 和JS:

var vel = 2000;
var degs = 0;
var cat = document.querySelector("img");
function repeat(){
  if(vel == 1000){
    cat.classList.add("hover");
    console.log("hover")
  }else{
    cat.classList.remove("hover");
    console.log("nohover")
  }
  degs+=360;
  cat.style.transform = "rotate("+degs+"deg)";
  setTimeout(repeat, vel);
}
repeat();
document.querySelector("img").addEventListener("mouseenter",hovering);
function hovering(){
  vel = 1000;
}
document.querySelector("img").addEventListener("mouseleave",nohovering);
function nohovering(){
  vel = 2000;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM