分享一个优化版网站下雪代码
JS代码// 下雪效果
function createSnowflake() {
const snowflake = document.createElement('div');
snowflake.classList.add('snowflake');
snowflake.innerHTML = '❄'; // 雪花的图标可以更改
const size = Math.random() * 20 + 10; // 雪花大小范围
let initialX = Math.random() * window.innerWidth;
snowflake.style.fontSize = `${size}px`;
snowflake.style.left = `${initialX}px`;
document.body.appendChild(snowflake);
setTimeout(() => {
snowflake.remove();
}, 10000); // 与动画时间一致
}
function snowfall() {
setInterval(createSnowflake, 300); // 控制雪花的生成速度
}
snowfall();
CSS代码
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
overflow: scroll;
overflow-x: hidden;
width: 100vw;
height: 100vh;
position: relative; /* 为伪元素定位做准备,添加相对定位 */
}
body::before {
content: "";
position: fixed; /* 设置为固定定位 */
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(
135deg,
hsl(170deg, 80%, 70%),
hsl(190deg, 80%, 70%),
hsl(250deg, 80%, 70%),
hsl(320deg, 80%, 70%)
);
background-size: 200% 200%;
animation: gradient-move 15s ease alternate infinite;
z-index: -1; /* 将其层级设置得较低,避免遮挡页面内容 */
}
@keyframes gradient-move {
0% {
background-position: 0% 0%;
}
100% {
background-position: 100% 100%;
}
}
页:
[1]