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>