【问题标题】:I'm using click event to trigger CSS animation, why wouldn't the animation run again when clicked again?我正在使用点击事件触发CSS动画,为什么再次点击时动画不会再次运行?
【发布时间】:2022-01-20 00:45:51
【问题描述】:

我是 Web 开发新手,我正在尝试更好地了解 DOM。

我的代码的目的是在触发点击事件时为元素提供一些动画。这是我尝试过的:

代码:

const svg = document.getElementById('svg');
const button = document.getElementById('button');

button.onclick = function() {
  svg.style.animation = 'svg-color 5s linear 1 1s';
}
svg {
  background-color: lightcyan;
}

@keyframes svg-color {
  0% {
    background-color: lightcyan;
  }
  50% {
    background-color: skyblue;
  }
  100% {
    background-color: steelblue;
  }
}
<svg id="svg" width="300" height="300"></svg>
<button id="button">button</button>

它适用于第一次点击事件。但是当我再次单击按钮时,动画将不再运行。

这个问题是由于 DOM 还是我在 CSS 上将 animation-iteration-count 设置为 1 的事实?

如果我将动画迭代计数设置为无限,有没有办法让动画回到它的开始状态并在点击事件时再次重播?

【问题讨论】:

  • 因为您分配的样式与已在元素上设置的样式相同。您应该在动画结束时移除样式。

标签: javascript html css animation dom


【解决方案1】:

如果您分配的样式已在元素上设置,则不会发生任何事情。

您需要在动画结束时移除样式。这样,下次单击时样式将是新的。

const svg = document.getElementById('svg');
const button = document.getElementById('button');

button.onclick = function() {
  svg.style.animation = 'svg-color 5s linear 1 1s';
}
svg.addEventListener("animationend", (e) => e.target.style.animation = '');
svg {
  background-color: lightcyan;
}

@keyframes svg-color {
  0% {
    background-color: lightcyan;
  }
  50% {
    background-color: skyblue;
  }
  100% {
    background-color: steelblue;
  }
}
<svg id="svg" width="300" height="300"></svg>
<button id="button">button</button>

【讨论】:

    猜你喜欢
    • 2017-08-06
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多