CSS animation-delay — затримка перед стартом анімації
Властивість animation-delay встановлює час очікування перед запуском циклу анімації. Значення 0s або 0ms запускає анімацію відразу ж. Негативне значення також вмикає анімацію без затримок, але може привести до зміни виду початку анімації. Наприклад, задаючи значення 5s, ми встановлюємо, що анімація запуститься після 5-ти секунд очікування.
Ви можете запустити анімацію у конкретний момент в майбутньому, відразу після її присвоєння елементу або відразу після початку циклу демонстрації анімації.
Допустимо вказувати кілька значень, перераховуючи їх через кому.
автор: Svitlana
Загальний опис
автор: NagarD
- Порада
-
Рекомендується використовувати універсальну властивість
автор: Svitlanaanimation, щоб задавати всі властивості відразу в одному місці. Це робить стилі більш зрозумілішими та зменшує їхній обсяг. - Порада
-
Зверніть увагу, що порядок у визначенні властивості має дуже важливий. Перше значення у формі часу, розглядається як
автор: Svitlanaanimation-duration, а друге - якanimation-delay.
Синтаксис
animation-delay: time|initial|inherit;
Властивість animation-delay може отримувати 3 значень:
-
time -
Необов`язково. Визначає кількість секунд/мілісекунд до початку анімації
автор: Svitlana -
initial -
Встановлює властивість у значення без задання
автор: Svitlana -
inherit -
Вказує на спадковість властивості від свого батьківського елемента
автор: Svitlana
| Значення без задання: | 0s |
|---|---|
| Наслідує: | Ні |
| Анімується: | Ні |
| JavaScript синтаксис: | object.style.animationDelay="1s" |
Переглядачі
| Переглядач | ||||||
|---|---|---|---|---|---|---|
| 43 | 16 | 9 | 30 | 12 | 10 |
| Переглядач | ||||
|---|---|---|---|---|
| 43 | 43 | 16 | 9 |
Приклади
+ запропонувати свій приклад у пісочниці
Інструмент
Складає кадри @keyframes і одразу програє їх.
Конструктор @keyframes — окремою сторінкою, з поясненням пасток.
Демонстрація дії різних значень властивості
HTML
<p>Спробуйте змінити значення для <code>animation-delay</code> (максимально 60, це для прикладу):</p>
<input type="number" value="0" max="60" id="field">
<button id="btn">Запустити анімацію</button>
<div id="block">
<span id="time">00s</span>
</div>
CSS
body {
padding: 36px;
text-align: center;
font-family: monospace;
font-size: 17px;
color: #222;
line-height: 1.45;
}
#field,
#btn{
padding: 6px 12px;
font-size: 19px;
display: inline-block;
}
#btn {
cursor: pointer;
width: 250px;
text-align: center;
}
@keyframes animate {
from {
margin-top: 50px;
}
to {
margin-top: 100px;
}
}
#block {
background-color: red;
padding: 36px 26px;
width: 75px;
margin-top: 50px;
text-align: center;
color: #fff;
font-size: 18px;
border: 2px solid rgba(255, 255, 255, .45);
animation: animate 1s ease-in 0s infinite alternate paused;
}
JS
var block = document.getElementById('block');
var field = document.getElementById('field');
var btn = document.getElementById('btn');
var time = document.getElementById('time');
field.onchange = function () {
block.style.animationDelay = field.value + 's';
};
btn.onclick = function () {
if (block.style.animationPlayState != 'running') {
var newTime = field.value;
startTimer(newTime);
block.style.animationPlayState = 'running';
btn.innerHTML = 'Зупинити анімацію';
} else {
block.style.animationPlayState = 'paused';
btn.innerHTML = 'Запустити анімацію';
startTimer(0);
}
};
function startTimer(duration) {
var timer = duration,seconds;
var showTime = setInterval(function () {
seconds = parseInt(timer % 60, 10);
seconds = seconds < 10 ? "0" + seconds : seconds;
time.innerText = seconds + 's';
if (--timer < 0) {
clearInterval(showTime);
}
}, 1000);
}
//# sourceURL=pen.js
Обидва блоки анімуються однаково, але другий стартує на 2 секунди пізніше. Затримка діє лише перед першим циклом — далі повтори йдуть без пауз.
HTML
<div class="box">без затримки</div>
<div class="box delayed">animation-delay: 2s</div>
CSS
.box {
width: 220px;
padding: 8px;
margin-bottom: 8px;
background: #0172ad;
color: #fff;
position: relative;
animation: mymove 3s infinite;
}
.delayed {
animation-delay: 2s;
background: #d81b60;
}
@keyframes mymove {
from { left: 0; }
to { left: 160px; }
}
Простий приклад дії властивості
HTML
<div class="info">
<p>За допомогою універсальної властивості <code>animation-delay</code> ми можемо встановити час очікування перед запуском циклу анімації.</p>
<p>Нижче, показаний приклад такої анімації. Ми визначили таймер на 4 секунди.</p>
</div>
<div id="time">4s</div>
<div class="wrapper">
<span id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</div>
CSS
* {
box-sizing: border-box;
}
body {
font-family: monospace;
font-size: 15px;
overflow: hidden;
line-height: 1.45;
}
.info {
padding: 6px;
}
code {
font-weight: 700;
color: #444;
border-bottom: 2px solid #666;
}
.wrapper {
background-color: #dcdcdc;
}
#text {
margin-top: 0;
display: block;
animation: anim 1.75s linear 10s infinite alternate none paused;
font-weight: 700;
padding: 8px 0;
text-align: center;
/*animation-delay: 2s;
animation-name: anim;
animation-play-state: paused;
animation-duration: .8s;
animation-iteration-count: infinite;
animation-timing-function: linear;*/
}
@keyframes anim {
0% { margin-top: 0; }
50% { margin-top: 50px; }
100% { margin-top: 0; }
}
JS
function startTimer() {
var timer = 10,seconds;
var showTime = setInterval(function () {
seconds = parseInt(timer % 60, 10);
document.getElementById('time').innerText = seconds + 's';
if (--timer < 0) {
clearInterval(showTime);
}
}, 1000);
}
window.onload = function () {
startTimer();
document.getElementById('text').style.animationPlayState = 'running';
};
//# sourceURL=pen.js
Коментарі
Коментарів ще немає — будьте першим!