2

CSS3 アニメーションまたは Web アニメーション ( ) による変更を検出するにはどうすればよいですElement.animateか??

(下手な英語でごめんなさい! これが Stackoverflow での最初の質問です)

MutationObserver については知っていますが、インライン スタイルを変更した場合、または使用した場合にのみ応答しますrequestAnimationFrame(それを使用してインライン スタイルを変更したため)。しかし、CSS3 アニメーションまたは Web アニメーションを使用すると、インライン スタイルが変更されないため、MutationObserver は応答しません。

これを参照してください... ここには 2 つの div があります... div1、div2。div2 の位置が変わると、div1 の位置も変わります。しかし、これは前に述べたように requestAnimationFrame を使用した場合にのみ発生します。

私の質問は、css3 アニメーションと Web アニメーション (Element.animate) でこれを行うにはどうすればよいですか?

const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');

/***** Add mutation observer to detect change *****/

const mutation = new MutationObserver(mutations => {
  div1.style.left = div2.style.left;
});

mutation.observe(div2, {
  attributes: true
});

/***** Animation with css *****/

function cssAnimation() {
  div2.style.animation = 'anim 1.5s linear';
}

/***** Animation with web animations *****/

function webAnimation() {
  div2.animate({
    left: [0, '500px']
  }, {
    duration: 1500,
    easing: 'linear'
  });
}

/*****Animation with requestAnimationFrame ******/

// Current left position of div2
const left = 0;

function requestAnimation() {
  // Increase left position 5px per keyframe
  div2.style.left = `${(left += 5)}px`;

  // Increase left position until it reaches to 500px
  if (left < 500) {
    requestAnimationFrame(requestAnimation);
  }
}

function clearAnimations() {
  left = 0;
  div2.style.left = 0;
  div2.style.animation = 'unset';
}
@keyframes anim {
  from {
    left: 0;
  }
  to {
    left: 500px;
  }
}

#div1 {
  background: orange;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 200px;
}

#div2 {
  background: lightgreen;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
}
<div id="buttons">
  <h3>Animate with...</h3>
  <button onclick='cssAnimation()'>Css3</button>
  <button onclick="requestAnimation()">request animation frame</button>
  <button onclick="webAnimation()">web animations api</button>
  <button id="clear" onclick="clearAnimations()">Clear</button>
</div>

<div id="div1">
  Div1
</div>
<div id="div2">
  div2
</div>

4

4 に答える 4

0

CSS アニメーションの場合、達成しようとしていることに役立つ可能性のある animationstart および animationend イベントがあります。ただし、 animationchangeまたはanimationupdateイベントはなく、私の知る限り、設計上はこのようになっています。アニメーション中にイベントが発生しなくても、補間計算を GPU で直接実行して、完全なハードウェア アクセラレーションに到達できます。したがって、animationstart、animationend、および requestAnimationFrame を介して animationchange イベントが行うことを模倣できるかもしれませんが、これにはおそらくパフォーマンスの低下が伴うことに注意してください。

于 2017-10-22T04:46:52.807 に答える
0

あなたは物事を複雑にしすぎています。ただし、アニメーションの変更をリッスンするには、ミューテーション オブザーバーの代わりにこれらのイベントをリッスンできます。

animationstart //will fire has soon as the animation starts
animationiteration //will fire if the same animation is looped can be infinity or more then 2
animationend // will fire when the animations have ended

また、左のプロパティをアニメーション化する代わりに、translate を使用してください。

于 2017-10-22T04:46:55.177 に答える