首页 > 解决方案 > 当`fill`是“转发”时如何在动画后执行程序化`transform`

问题描述

在使用动画 API 为元素设置动画后,transform如果animation-fill-mode属性设置为 true,我将无法执行另一个。

考虑以下脚本:

var elem = document.querySelector('#box');

document.querySelector("#translate").addEventListener('click', () => {
  elem.style.transform = "rotate(45deg)"
})

document.querySelector("#animate").addEventListener('click', () => {
  var animation = elem.animate({
    opacity: [0.5, 1],
    transform: ['translateX(0)', 'translateX(25px)'],
  }, {
    duration: 500,
    iterations: 1,
    // Change this value to "auto" or "none" for expected behavior
    fill: "forwards"
  });
})

如果单击#animate按钮,我希望看到动画执行。这确实发生了。动画完成并且元素向右多出 25px 后,#translate(最好命名为#transform)按钮在单击时不再执行旋转。

fill如果属性不是“向前”或“两者” ,它会正确旋转元素。

JSBin 示例

标签: javascriptcss-animations

解决方案


我有一个黑客解决方案。我会把它贴在这里,但理想情况下,存在一个不是这个的解决方案。

似乎取消动画会“解锁”要再次转换的元素。

const elem = document.querySelector('#box');

document.querySelector('#translate').addEventListener('click', () => {
  elem.style.transform = elem.style.transform + ' rotate(45deg)';
});

document.querySelector('#animate').addEventListener('click', () => {
  const animationDuration = 500;
  const targetTranslation = 'translateX(25px)';

  const animation = elem.animate({
    transform: ['translateX(0)', targetTranslation],
  }, {
    duration: animationDuration,
    iterations: 1,
    // Change this value to "auto" or "none" for expected behavior
    fill: 'forwards'
  });

  setTimeout(() => {
    animation.cancel();
    elem.style.transform = targetTranslation;
  }, animationDuration);
});

JSBin 示例


推荐阅读