Я пытаюсь анимировать буквы, чтобы они летали из случайных позиций, используя JavaScript. Он работает отлично. Однако когда я добавляю кнопку в HTML, анимация больше не работает должным образом — буквы появляются в центре, а не вылетают из случайных позиций. Как я могу это исправить, сохраняя кнопку в том же контейнере?
Вот мой код:
HTML:
L
e
t
'
s
o
r
g
a
n
i
z
e
e
v
e
r
y
t
h
i
n
g
body {
background-color: #282c34;
color: #fff;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
}
.container {
display: flex;
flex-wrap: wrap;
gap: 5px;
font-size: 2rem;
font-weight: bold;
text-align: center;
position: relative;
}
.letter {
position: relative;
opacity: 0;
animation: flyIn 1.5s ease forwards;
}
button {
position: relative;
margin-top: 20px;
padding: 10px 20px;
background-color: #61dafb;
color: #282c34;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
}
button:focus {
outline: none;
}
button:hover {
background-color: #21a1f1;
}
@keyframes flyIn {
from {
opacity: 0;
transform: translate(var(--random-x), var(--random-y));
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
const letters = document.querySelectorAll('.letter');
function animateLetters() {
letters.forEach((letter, index) => {
// Generate rarndom initial positions
const randomX = (Math.random() - 0.5) * window.innerWidth; // Random X
const randomY = (Math.random() - 0.5) * window.innerHeight; // Random Y
// Apply CSS variables for animation
letter.style.setProperty('--random-x', `${randomX}px`);
letter.style.setProperty('--random-y', `${randomY}px`);
// Add staggered delay for smooth animation
letter.style.animationDelay = `${index * 0.2}s`;
});
}
// Trigger animation on load
animateLetters();
Подробнее здесь: https://stackoverflow.com/questions/793 ... javascript