Элемент: событие animationcancel
Событие animationcancel срабатывает, когда анимация CSS неожиданно прерывается. Другими словами, в любой момент, когда она останавливается, не отправив событие animationend. Это может произойти, когда свойство animation-name изменяется таким образом, что анимация удаляется, или когда анимируемый узел скрывается с помощью CSS. Следовательно, либо напрямую, либо потому, что любой из его родительских узлов скрыт.
Обработчик этого события можно добавить, установив свойство onanimationcancel или используя addEventListener().
Синтаксис
Используйте имя события в методах, таких как addEventListener(), или установите свойство обработчика события.
addEventListener("animationcancel", (event) => {});
onanimationcancel = (event) => {};
Тип события
Объект AnimationEvent. Наследуется от Event.
Свойства события
Также наследует свойства от своего родителя Event.
-
AnimationEvent.animationNameТолько для чтения -
Строка, содержащая значение свойства
animation-name, которое сгенерировало анимацию. -
AnimationEvent.elapsedTimeТолько для чтения -
Значение с плавающей точкой, указывающее на продолжительность выполнения анимации в секундах в момент срабатывания события, исключая время, когда анимация была приостановлена. Для события
animationstart,elapsedTimeравно0.0, если не было отрицательного значения дляanimation-delay, в противном случае событие будет выполнено со значениемelapsedTime, содержащим(-1 * delay). -
AnimationEvent.pseudoElementТолько для чтения -
Строка, начинающаяся с
'::', содержащая имя псевдоэлемента псевдоэлемента, на котором выполняется анимация. Если анимация не выполняется на псевдоэлементе, а на элементе, то строка пуста:''.
Примеры
Этот код получает элемент, который в данный момент анимируется, и добавляет обработчик события animationcancel. Затем он устанавливает свойство display элемента в значение none, что вызовет событие animationcancel.
const animated = document.querySelector(".animated");
animated.addEventListener("animationcancel", () => {
console.log("Animation canceled");
});
animated.style.display = "none";
То же самое, но с использованием свойства onanimationcancel вместо addEventListener():
const animated = document.querySelector(".animated");
animated.onanimationcancel = () => {
console.log("Animation canceled");
};
animated.style.display = "none";
Пример
HTML
<div class="animation-example">
<div class="container">
<p class="animation">You chose a cold night to visit our planet.</p>
</div>
<button class="activate" type="button">Activate animation</button>
<div class="event-log"></div>
</div>
CSS
.container {
height: 3rem;
}
.event-log {
width: 25rem;
height: 2rem;
border: 1px solid black;
margin: 0.2rem;
padding: 0.2rem;
}
.animation.active {
animation-duration: 2s;
animation-name: slide-in;
animation-iteration-count: 2;
}
@keyframes slide-in {
from {
transform: translateX(100%) scaleX(3);
}
to {
transform: translateX(0) scaleX(1);
}
}
JavaScript
const animation = document.querySelector("p.animation");
const animationEventLog = document.querySelector(
".animation-example>.event-log",
);
const applyAnimation = document.querySelector(
".animation-example>button.activate",
);
let iterationCount = 0;
animation.addEventListener("animationstart", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
});
animation.addEventListener("animationiteration", () => {
iterationCount++;
animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
});
animation.addEventListener("animationend", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
animation.classList.remove("active");
applyAnimation.textContent = "Activate animation";
});
animation.addEventListener("animationcancel", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
});
applyAnimation.addEventListener("click", () => {
animation.classList.toggle("active");
animationEventLog.textContent = "";
iterationCount = 0;
const active = animation.classList.contains("active");
applyAnimation.textContent = active
? "Cancel animation"
: "Activate animation";
});
Результат
Спецификации
Совместимость с браузерами
| Рабочие столы | Мобильные устройства | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | |
animationcancel_event |
83Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
83Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
54 | 69Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
13.112–13.1Несмотря на поддержку свойства обработчика событияonanimationcancel, событие animationcancel никогда не генерируется. |
83Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
54 | 59Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
13.412–13.4Несмотря на поддержку свойства обработчика событияonanimationcancel, событие animationcancel никогда не генерируется. |
13.0Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
83Свойство обработчика событияonanimationcancel не поддерживается. Для прослушивания этого события используйте element.addEventListener('animationcancel', function() {});. См. ошибку 41404325. |
См. также
- CSS Анимации
- Использование CSS анимаций
AnimationEvent- Связанные события:
animationstart,animationend,animationiteration
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/animationcancel_event