Năm nào cũng có giáng sinh, vì thế cứ tới mùa giáng sinh thì mọi web đều đua nhau tô lên những không khí đúng chất của nó. Để làm được 1 site tuyết rơi, vô cùng đơn giản, hãy lướt qua đều đều bài viết dưới nhé.
Hãy chèn đoạn code sau vào thẻ script
// snowfall.js function createSnowflake() { const snowflake = document.createElement('div'); snowflake.classList.add('snowflake'); // Thiết lập vị trí ngẫu nhiên từ trái sang phải snowflake.style.left = Math.random() * window.innerWidth + 'px'; // Kích thước ngẫu nhiên const size = Math.random() * 5 + 2; snowflake.style.width = size + 'px'; snowflake.style.height = size + 'px'; // Tốc độ rơi ngẫu nhiên snowflake.style.animationDuration = (Math.random() * 3 + 2) + 's'; document.body.appendChild(snowflake); // Xóa snowflake khi rơi xuống setTimeout(() => { snowflake.remove(); }, 5000); } // CSS để tạo hiệu ứng tuyết function addSnowfallStyles() { const style = document.createElement('style'); style.textContent = ` .snowflake { position: fixed; top: -10px; background-color: white; border-radius: 50%; pointer-events: none; z-index: 9999; animation: fall linear infinite; opacity: 0.7; } @keyframes fall { to { transform: translateY(100vh) rotate(360deg); } } `; document.head.appendChild(style); } // Tạo tuyết liên tục function startSnowfall() { // Thêm styles addSnowfallStyles(); // Tạo tuyết setInterval(createSnowflake, 200); } // Bắt đầu hiệu ứng khi trang tải window.addEventListener('load', startSnowfall);
Hoàn tất, nếu muốn đổi màu của tuyết, hãy đổi dòng CSS
background-color: white; // đổi white thành mã màu hoặc tên màu yêu thích