下雪效果(html+js)

下雪效果(html+js)

本文展示了一个使用JavaScript和CSS实现的网页下雪动画效果。通过创建200个随机大小(3-8px)的圆形雪花元素,设置随机位置、下落速度和水平飘移幅度,配合CSS动画实现自然飘落效果。雪花采用box-shadow发光效果,增强视觉表现。代码包含完整的HTML结构和JavaScript实现,通过改变随机参数可调整雪花的密度、速度和发光强度。该效果适合用作冬季主题网站的装饰背景。

实现方法:

js 文件

document.addEventListener("DOMContentLoaded", function () {

const snowflakesContainer = document.getElementById("snowflakes");

const snowflakeCount = 200; // 雪花数量

for (let i = 0; i < snowflakeCount; i++) {

const snowflake = document.createElement("div");

snowflake.classList.add("snowflake");

const size = Math.random() * 5 + 3; // 随机大小

const left = Math.random() * 100; // 随机水平位置

const duration = Math.random() * 10 + 10; // 随机下落时间

const delay = Math.random() * 10; // 随机动画延迟

const horizontalMovement = Math.random() * 50 - 25; // 随机水平漂移

// 设置雪花的样式

snowflake.style.width = `${size}px`;

snowflake.style.height = `${size}px`;

snowflake.style.left = `${left}%`;

snowflake.style.animation = `snowfall ${duration}s linear ${delay}s infinite`;

// 随机初始位置,避免雪花都在顶部开始

const initialTop = Math.random() * 100; // 随机初始垂直位置

snowflake.style.top = `${initialTop}vh`;

snowflake.style.transform = `translateX(${horizontalMovement}px)`;

// 设置动画的起始位置

snowflake.style.animationPlayState = "paused";

snowflake.style.animationDelay = `-${(initialTop / 100) * duration}s`;

snowflake.style.animationPlayState = "running";

// 使用 box-shadow 实现发光效果

snowflake.style.boxShadow = `0 0 ${size * 2}px rgba(255, 255, 255, 0.8)`;

snowflake.style.borderRadius = "50%";

snowflake.style.background = "white";

snowflakesContainer.appendChild(snowflake);

}

});

html,引用上面的js

下雪效果

相关任务