Анимация слов на HTML CSS JS
Подскажите пожалуйста как сделать на HTML, CSS, JS так, чтобы курсор "|" когда возвращается налево он заменял слово на другое + на новый "цвет"-"background-color" и потом через 5 секунд снова возращялся направо и изменял всё. Вот как то так: (код я ещё не дописала, потому что не пойму как, нигде в интернете ответ найти не могу. Заранее спасибо!)
Эффект должен выглять как на картинке, но вместо картинок долны быть слова:
* {
box-sizing: border-box;
}
body {
padding: 50px;
}
.container {
overflow: hidden;
}
.is-animated {
font-family: 'Helvetica Neue';
font-weight: bold;
padding: 0;
position: relative;
background-color: rgba(255, 146, 246, 0.651);
}
.is-animated span {
display: block;
}
.property {
font-size: 150%;
text-align: right;
border-right: 2px solid #000;
width: 0;
overflow: hidden;
float: left;
-webkit-animation-name: expandProperty;
-webkit-animation-delay: .5s;
-webkit-animation-duration: .8s;
-webkit-animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in;
}
@-webkit-keyframes expandProperty {
from {
width: 0px;
}
to {
width: 100px;
}
}
<div class="container">
<div class="property is-animated">
<span>text</span>
</div>
</div>
let words = [
"text1",
"text2",
"text3",
"text4",
"text5",
"text6",
"text7"
];
let colors = [
"#0a009d",
"#f91d92",
"#38bc4c",
"#ffce1e",
"#00bbf9 ",
"#9f2dd4",
"#19ddbf",
];
let currentWord = 0;
let intervalid = setInterval(()=>{
if (currentWord == words.length - 1)
currentWord = 0;
else
currentWord++;
let obj = document.getElementById("word");
obj.style.backgroundColor = colors[currentWord];
obj.innerText = words[currentWord];
}, 600);
* {
box-sizing: border-box;
}
body {
padding: 50px;
}
.container {
overflow: hidden;
}
.is-animated {
font-family: 'Helvetica Neue';
font-weight: bold;
padding: 0;
position: relative;
background-color: rgba(255, 146, 246, 0.651);
}
.is-animated span {
display: block;
}
.property {
font-size: 150%;
text-align: right;
border-right: 2px solid #000;
width: 0;
overflow: hidden;
float: left;
-webkit-animation-name: expandProperty;
-webkit-animation-delay: .5s;
-webkit-animation-duration: .8s;
-webkit-animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in;
animation : expandProperty 10s infinite forwards;
}
@-webkit-keyframes expandProperty {
from {
width: 0px;
}
to {
width: 100px;
}
}
@keyframes expandProperty {
0% {
width: 0px;
}
50% {
width: 100px;
}
100% {
width: 0px;
}}
<div class="container">
<div class="property is-animated">
<span id="word">text</span>
</div>
</div>
Ответы (2 шт):
Как вариант использовать js функцию setInterval и устанавливать нужный вам стиль.
Если через css, можно как-то так:
animation: expandProperty 10s infinite forwards;
@keyframes expandProperty {
0% {
width: 0px;
}
50% {
width: 100px;
}
100% {
width: 0px;
}
Если я правильно понял, вы хотите анимировать несколько строк, без JS будет тяжко, придётся высчитывать таймлайн вручную, например как в примере:
.print-text {
white-space: nowrap;
font-size: 0;
}
.print-text-item {
display: inline-block;
width: 0;
font-size: 20px;
overflow: hidden;
text-overflow: '';
font-family: monospace;
text-transform: uppercase;
animation: none 12s step-end infinite; /* Вся анимация будет выполняться 12 секунд */
}
.print-text-item--1 {
height: 25px;
line-height: 25px;
background-color: red;
color: #fff;
animation-name: print-1; /* Каждый элемент со своей анимацией, которая разбита по таймлайну, чтобы имитировать задержку и воспроизводить анимацию зациклено */
}
.print-text-item--2 {
height: 25px;
line-height: 25px;
background-color: blue;
color: #fff;
animation-name: print-2;
}
.print-text-item--3 {
height: 25px;
line-height: 25px;
background-color: yellow;
color: #000;
animation-name: print-3;
}
.print-text-cr {
display: inline-block;
width: 1px;
height: 25px;
background-color: #000;
animation: cr 1s step-end infinite;
margin-left: 4px;
}
@keyframes cr {
0%, 100% {opacity: 0;}
50% {opacity: 1;}
}
/*
Везде используется animation-timing-function: step-end, чтобы анимация больше похожа была на печать.
Для этого весь тайлайн разбит на куски, на каждую букву свой отдельный "участок".
*/
@keyframes print-1 { /* в слове HTML - 4 буквы */
2.5%, 27.5% {width: 1ch;}
5%, 25% {width: 2ch;}
7.5%, 22.5% {width: 3ch;}
10%, 20% {width: 4ch;}
0%, 30%, 100% {width: 0;}
}
@keyframes print-2 { /* в слове CSS - 3 буквы */
32.5%, 57.5% {width: 1ch;}
35%, 55% {width: 2ch;}
37.5%, 52.5% {width: 3ch;}
0%, 60%, 100% {width: 0;}
}
@keyframes print-3 { /* в слове JAVASCRIPT - 10 буквы */
61%, 89% {width: 1ch;}
62%, 88% {width: 2ch;}
63%, 87% {width: 3ch;}
64%, 86% {width: 4ch;}
65%, 85% {width: 5ch;}
66%, 84% {width: 6ch;}
67%, 83% {width: 7ch;}
68%, 82% {width: 8ch;}
69%, 81% {width: 9ch;}
70%, 80% {width: 10ch;}
0%, 90%, 100% {width: 0;}
}
/*
Так же, чтобы исключить разную ширину символов - используется monospace шрифт (одинаковая ширина символов) и единица измерения CH (загуглить).
*/
<div class="print-text">
<span class="print-text-item print-text-item--1"><span>HTML</span></span>
<span class="print-text-item print-text-item--2"><span>CSS</span></span>
<span class="print-text-item print-text-item--3"><span>JavaScript</span></span>
<span class="print-text-cr"></span>
</div>
По этому лучше заюзать JS.
Например так: (первое что пришло в сонную голову)
var symTick = 100; // Сколько мс выделяется на 1 букву.
var delay = 500;
var active = 0; // Какой текст воспроизводится
var buffer = [];
var printTextItem = document.querySelectorAll('.print-text-item');
printTextItem.forEach(function(item) {
var text = item.textContent.trim();
buffer.push({
len: text.length,
text: text,
cls: item.classList
});
item.remove();
});
StartPrint(document.querySelector('.print-text'), active);
function StartPrint(parent, index) {
parent.innerHTML = '';
var data = buffer[index];
var i = 0;
var el = document.createElement('span');
el.classList = data.cls;
parent.append(el);
var timer = setInterval(function() {
if(i < data.len) {
el.textContent += data.text[i];
i++;
} else {
clearInterval(timer);
setTimeout(DeleteTextTick, delay);
}
}, symTick);
function DeleteTextTick() {
i = 0;
timer = setInterval(function() {
if(i < data.len) {
el.textContent = el.textContent.slice(0, -1);
console.info(el.textContent);
i++;
} else {
clearInterval(timer);
active = active + 1 < buffer.length ? active + 1 : 0;
setTimeout(StartPrint(parent, active), delay);
}
}, symTick / 2);
}
}
.print-text {
font-size: 20px;
}
.print-text::after {
content: '';
display: inline-block;
width: .1ch;
height: 1em;
background-color: #000;
animation: cr 1s step-end infinite;
vertical-align: bottom;
margin-left: .3ch;
}
.print-text-item.red {
background-color: red;
color: #fff;
}
.print-text-item.blue {
background-color: blue;
color: #fff;
}
.print-text-item.yellow {
background-color: yellow;
color: #000;
}
@keyframes cr {
0%, 100% {opacity: 0;}
50% {opacity: 1;}
}
<div class="print-text">
<span class="print-text-item red">HTML</span>
<span class="print-text-item blue">CSS</span>
<span class="print-text-item yellow">JavaScript</span>
</div>

