繁体   English   中英

为什么我不能修改属性 js animate() 应用于元素?

[英]Why can't I modify the property js animate() applies to an element?

animation 完成后,点击事件将不再起作用,实际上从开发工具更改值也不起作用。 使用fill: 'none'会起作用,但我想使用 animation 应用的样式。

这是预期的行为吗? animation 完成并将样式作为内联style应用于元素(或者是吗?),为什么在这种情况下不能修改? 有没有办法保持 animation 应用的样式然后修改它?

示例:在 animation 完成后,事件监听器不再工作

 let square = document.querySelector('.circle') square.addEventListener('click', () => { square.style.transform = 'translateY(50px)' }) let animation = [ {transform: 'translateY(100px)'} ] square.animate(animation, {duration: 2000, fill: 'both'})
 .circle { width: 100px; height: 100px; background-color: #c965a6; border-radius: 50%; }
 <div class='circle'></div>

编辑:找到解决方案

使用fill: 'none' ,监听 animation 何时完成并手动将最终样式应用于元素。

let anim = square.animate(animation, {duration: 2000, fill: 'none'})
anim.addEventListener('finish', () => {
  square.style.transform = 'translateX(0px)'
})

尽管这似乎更像是一种解决方法,但我仍然想知道为什么您不能修改 animation 应用的属性

您可以cancel()您的 Animation,以便消除其影响。

 // Beware I renamed your variables so they match better (except for the triangle of course:P) const square = document.querySelector('.circle') const keyframes = [ {transform: 'translateY(100px)'} ] const animation = square.animate(keyframes, {duration: 2000, fill: 'both'}) square.addEventListener('click', () => { animation.cancel(); square.style.transform = 'translateY(50px)' })
 .circle { width: 100px; height: 100px; background-color: #c965a6; border-radius: 50%; }
 <div class='circle'></div>

这就是 Web 动画 API (WAAPI) 用于 function 的方式。 Styles applied by the API take precedence over all other css styles, even inline styles, unless important is applied to the inline style. 顺便说一句,API 不会更改样式属性,而是在 WAAPI 上下文中应用 styles。 您可以通过调用el.getAnimations()获取由 Animations API 应用的 styles。

应用 WAAPI 样式后,您可以通过两种方式应用 styles:

  1. 使用important ,像这样:

square.style.setProperty( 'transform', 'translateY(0px)', 'important' );

  1. 取消整个 animation 然后应用一个样式: anim.cancel();

 let square = document.querySelector('.circle'); square.style.transform = 'translateY(50px)'; square.addEventListener('click', () => { anim.cancel(); square.style.transform = 'translateY(0px)'; }); let animation = [ {transform: 'translateY(100px)'} ]; let anim = square.animate(animation, {duration: 2000, fill: 'both'});
 .circle { width: 100px; height: 100px; background-color: #c965a6; border-radius: 50%; }
 <div class='circle' ></div>

暂无
暂无

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

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