Да, мы можем динамически создавать, применять и удалять анимацию CSS3 для элемента на странице.
Чтобы динамически создавать анимацию, нам нужно использовать функции insertRule
или addRule
, чтобы добавить @keyframes
правила и добавить их в таблицу стилей. После добавления анимации применить ее к элементу очень просто, нам просто нужно установить необходимое значение свойства для свойства animation
с помощью встроенных стилей. Удалить его очень просто, нам просто нужно вернуть значение null, когда его нужно удалить.
В приведенном ниже фрагменте я сначала вставил анимацию и применил ее к элементу при загрузке. Когда начинается анимация, элемент запускает событие animationstart
. В этом прослушивателе событий я получил outerHTML
элемента, который анимируется, и распечатал его, чтобы показать, как присутствует встроенный стиль, а затем в конце анимации (с помощью прослушивателя событий animationend
) я удалил встроенный style и напечатал outerHTML
после него, чтобы показать, что у него больше нет анимации.
Нет других более простых способов динамического создания анимации CSS3. Все возможные решения будут включать создание и добавление @keyframes
к таблицам стилей с использованием базовой insertRule
, addRule
или специальной функции appendRule
для ключевых кадров (которая используется для добавления правил к существующему ключевому кадру).
var elm = document.querySelector('.to-animate');
var op = document.querySelector('.output');
var animName = "shake-up-down",
animDuration = "3s",
animTiming = "linear",
animFillMode = "forwards",
animIteration = "3";
var ruleText = "0% {transform: translateY(0px);}";
ruleText += "25% {transform: translateY(10px);}";
ruleText += "75% {transform: translateY(-10px);}";
ruleText += "100% {transform: translateY(0px);}";
/* From David Walsh's blog */
function addCSSAnimRule(sheet, name, rules, index) {
if ("insertRule" in sheet) {
sheet.insertRule("@keyframes " + name + "{" + rules + "}", index);
} else if ("addRule" in sheet) {
sheet.addRule("@keyframes " + name, rules, index);
}
}
/* Self written */
function applyAnimation(elm, name, duration, timing, iteration, fillmode) {
elm.style["animation"] = name + " " + duration + " " + timing + " " + iteration + " " + fillmode;
/* or if you want to set them individually, comment the above line and uncomment this
elm.style["animationName"] = name;
elm.style["animationDuration"] = duration;
elm.style["animationTimingFunction"] = timing;
elm.style["animationIterationCount"] = iteration
elm.style["animationFillMode"] = fillmode;*/
}
addCSSAnimRule(document.styleSheets[0], animName, ruleText, 0);
applyAnimation(elm, animName, animDuration, animTiming, animIteration, animFillMode);
/* to print output */
elm.addEventListener("animationstart", function(e) {
op.textContent = "Animation " + e.animationName + " has started.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
elm.addEventListener("animationend", function(e) {
elm.removeAttribute("style"); /* remove the animation */
op.textContent += "\nAnimation " + e.animationName + " has ended.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
.to-animate {
height: 100px;
width: 100px;
margin: 10px;
border: 1px solid red;
}
<div class='to-animate'></div>
<pre class='output'></pre>
Этот метод можно использовать для динамического создания и использования анимации любого типа. Ниже фрагмент создает и добавляет background-color
анимацию.
var elm = document.querySelector('.to-animate');
var op = document.querySelector('.output');
var animName = "bgColor",
animDuration = "4s",
animTiming = "linear",
animFillMode = "forwards",
animIteration = "3";
var ruleText = "0% {background-color: red;}";
ruleText += "25% {background-color: orange;}";
ruleText += "50% {background-color: yellow;}";
ruleText += "75% {background-color: pink;}";
ruleText += "100% {background-color: red;}";
/* From David Walsh's blog */
function addCSSAnimRule(sheet, name, rules, index) {
if ("insertRule" in sheet) {
sheet.insertRule("@keyframes " + name + "{" + rules + "}", index);
} else if ("addRule" in sheet) {
sheet.addRule("@keyframes " + name, rules, index);
}
}
/* Self written */
function applyAnimation(elm, name, duration, timing, iteration, fillmode) {
elm.style["animation"] = name + " " + duration + " " + timing + " " + iteration + " " + fillmode;
/* or if you want to set them individually, comment the above line and uncomment this
elm.style["animationName"] = name;
elm.style["animationDuration"] = duration;
elm.style["animationTimingFunction"] = timing;
elm.style["animationIterationCount"] = iteration
elm.style["animationFillMode"] = fillmode;*/
}
addCSSAnimRule(document.styleSheets[0], animName, ruleText, 0);
applyAnimation(elm, animName, animDuration, animTiming, animIteration, animFillMode);
/* to print output */
elm.addEventListener("animationstart", function(e) {
op.textContent = "Animation " + e.animationName + " has started.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
elm.addEventListener("animationend", function(e) {
elm.removeAttribute("style"); /* remove the animation */
op.textContent += "\nAnimation " + e.animationName + " has ended.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
.to-animate {
height: 100px;
width: 100px;
margin: 10px;
background-color: red;
}
<div class='to-animate'></div>
<pre class='output'></pre>
Кроссбраузерная версия:
Здесь кроссбраузерная версия с поддержкой старых браузеров с использованием методов, предоставляемых бесплатной библиотекой Prefix. Это было протестировано в IE10 +, Edge, Chrome v50 (dev-m), Firefox v43, Opera v35. Тестирование версии с префиксом проводилось в Safari 5.1.7 на Win 10.
person
Harry
schedule
06.02.2016