如何检测由css3动画或网页动画(Element.animate)所做的更改?如何检测由CSS3动画或Web动画API所做的更改?
(对不起,我的英文不好!这是我在#1的第一个问题)
我知道MutationObserver,它只是如果我改变内嵌样式或者如果我使用requestAnimationFrame(因为我用它更改内联样式)响应。但是如果我使用css3动画或Web动画,MutationObserver不会响应,因为它们不会更改内联样式。
看到这里...这里有两个div ... div1,div2。当div2的位置改变时,div1的位置将会改变。但是这只有在我使用requestAnimationFrame的时候才会发生。
我的问题是我怎样才能做到这一点的css3动画和网页动画(Element.animate)?
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
/***** Add mutation observer to detect change *****/
var mutation = new MutationObserver(function(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
var 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>
什么时候你想检测到CSS的变化? – guest271314
我知道我可以使用animationstart并通过setInterval进行更新,直到animationend事件发生时发生clearInterval。但它有性能问题。 –
@IbrahimAlKhalil你为什么要用setInterval?绝对没有必要。请阅读css动画和课程。你正在接近这完全错误的。 – Darkrum