在悬停时更改 SVG 动画

时间:2021-03-10 17:27:11

标签: css animation svg css-animations svg-animate

我有一个简单的 SVG 圆,它有一个默认的动画,悬停时动画会改变,但两者之间有一个笨拙的过渡。非常感谢您在这方面的帮助。

这是小提琴: https://jsfiddle.net/nLoa5t3u/

 
 svg {
    width: 250px;
    overflow: visible;
  }
  
  .circle {
    fill: none;
    stroke: red;
    stroke-width: 10;
    stroke-miterlimit: 10;
    stroke-linecap: round;
    transform-box: fill-box;
    transform-origin: center;
    animation: circleOneStroke 50s linear infinite forwards;
  }
  
  @keyframes circleOneStroke {
    0% {
      transform: rotate(0);
      stroke-dasharray: 400;
      stroke-dashoffset: 200;
    }


    100% {
      transform: rotate(1800deg);
      stroke-dasharray: 400;
      stroke-dashoffset: 200;
    }
  }
  
    svg:hover .circle {
    animation: circleOneStrokeHover 2s linear infinite forwards;
  }

@keyframes circleOneStrokeHover {

    0% {
      transform: rotate(0);
      animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
      stroke-dasharray: 400;
      stroke-dashoffset: 200;
    }

    10% {
      transform: rotate(0);
      animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
      stroke-dasharray: 400;
      stroke-dashoffset: 200;
    }

    50% {
      transform: rotate(900deg);
      animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
      stroke-dasharray: 500;
      stroke-dashoffset: 200;
    }

    100% {
      stroke-dasharray: 200;
      stroke-dashoffset: 300;
    }
  }
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1"
        x="0px" y="0px" viewBox="0 0 505 505" style="enable-background:new 0 0 505 505;" xml:space="preserve">
        <path class="circleThree circle"
          d="M502.5,252.5c0,138.07-111.93,250-250,250s-250-111.93-250-250s111.93-250,250-250S502.5,114.43,502.5,252.5z" />
      </svg>
      

1 个答案:

答案 0 :(得分:1)

当您悬停时,仅更改 animation-duration。尽管这确实意味着您自定义悬停动画的选项更加有限。

svg {
  width: 250px;
  overflow: visible;
}
  
.circle {
  fill: none;
  stroke: red;
  stroke-width: 10;
  stroke-miterlimit: 10;
  stroke-linecap: round;
  transform-box: fill-box;
  transform-origin: center;
  animation: circleOneStroke 50s linear infinite forwards;
}
  
@keyframes circleOneStroke {
  0% {
    transform: rotate(0);
    stroke-dasharray: 400;
    stroke-dashoffset: 200;
  }

  100% {
    transform: rotate(1800deg);
    stroke-dasharray: 400;
    stroke-dashoffset: 200;
  }
}
  
svg:hover .circle {
  animation-duration: 2s;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1"
     x="0px" y="0px" viewBox="0 0 505 505" style="enable-background:new 0 0 505 505;" xml:space="preserve">
  <path class="circleThree circle"
     d="M502.5,252.5c0,138.07-111.93,250-250,250s-250-111.93-250-250s111.93-250,250-250S502.5,114.43,502.5,252.5z" />
</svg>