首页 > 解决方案 > 悬停时的 SVG 抖动动画

问题描述

当您将鼠标悬停在它上面时,我正在尝试使用 CSS 关键帧进行 svg img 抖动。

这是我想要达到的效果:https ://www.w3schools.com/code/tryit.asp?filename=FZ7CQHXPG42J

有一些 javascript 可以为相同的 svg 设置动画,但它以父 div #ellipse 为目标,当单击汉堡包图标时,它会从左向右移动。我看不出它会如何干扰,但我添加它只是为了确保。

我在下面添加了相关代码。有关完整代码,请参阅网站。

// Other unrelated(!?) animations on #ellipse //

function moveEllipseRight() {
  ellipse.animate([
    // keyframes
    {
      transform: 'translateX(0px)'
    },
    {
      transform: 'translateX(' + width + 'px)'
    }
  ], {
    // timing options
    duration: 500,
    iterations: 1,
    easing: 'ease-in-out',
    fill: 'forwards'
  });
}

function moveEllipseLeft() {
  ellipse.animate([
    // keyframes
    {
      transform: 'translateX(' + width + 'px)'
    },
    {
      transform: 'translateX(0px)'
    }
  ], {
    // timing options
    duration: 500,
    iterations: 1,
    easing: 'ease-in-out',
    fill: 'forwards'
  });
}
#ellipse {
  position: absolute;
  top: 120px;
  z-index: -99;
  animation: 3s linear 0s slide 1;
  left: -200px;
}

img.shake:hover {
  animation: shake 0.5s;
  animation-iteration-count: infinite;
}

@keyframes shake {
  0% {
    transform: translate(1px, 1px) rotate(0deg);
  }
  10% {
    transform: translate(-1px, -2px) rotate(-1deg);
  }
  20% {
    transform: translate(-3px, 0px) rotate(1deg);
  }
  30% {
    transform: translate(3px, 2px) rotate(0deg);
  }
  40% {
    transform: translate(1px, -1px) rotate(1deg);
  }
  50% {
    transform: translate(-1px, 2px) rotate(-1deg);
  }
  60% {
    transform: translate(-3px, 1px) rotate(0deg);
  }
  70% {
    transform: translate(3px, 1px) rotate(-1deg);
  }
  80% {
    transform: translate(-1px, -1px) rotate(1deg);
  }
  90% {
    transform: translate(1px, 2px) rotate(0deg);
  }
  100% {
    transform: translate(1px, -2px) rotate(-1deg);
  }
}
<div id="ellipse">
  <img src="https://lh5.googleusercontent.com/-yqttzktPkDY/AAAAAAAAAAI/AAAAAAAABGU/z6CVGRmY-C8/photo.jpg?sz=328" alt="ellipse" class="shake" width="400" height="400" />
</div>

标签: cssanimationsvg

解决方案


问题在于你的#ellipse风格。

#ellipse {
    position: absolute;
    top: 120px;
    z-index: -99; /* remove this, it is not doing anything useful. */ 
    animation: 3s linear 0s slide 1;
    left: -200px;
}

问题是,悬停根本没有被触发,因为它在container元素后面是负z-index的。这个负 z 索引根本没有用,除非您打算将文本放在图像上方,我在您的网站上看不到。


推荐阅读