HTML制作动态背景飘落
时间: 2023-08-24 16:04:05 浏览: 84
你可以使用CSS3动画和JavaScript实现网页背景飘落的效果。以下是一个简单的示例代码:
HTML:
```html
<div class="snowflakes"></div>
```
CSS:
```css
.snowflakes {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
pointer-events: none;
}
.snowflakes:before {
content: '❄';
color: #fff;
font-size: 2em;
position: absolute;
top: 0;
animation: snowflakes 5s linear infinite;
}
@keyframes snowflakes {
0% {
transform: translateY(-50px);
}
100% {
transform: translateY(100vh);
}
}
```
JavaScript:
```javascript
// 窗口大小改变时重新计算位置
window.addEventListener('resize', () => {
const snowflakes = document.querySelectorAll('.snowflakes:before');
snowflakes.forEach((snowflake) => {
snowflake.style.left = `${Math.random() * window.innerWidth}px`;
snowflake.style.animationDelay = `${Math.random() * 5}s`;
});
});
// 初始化位置和延迟时间
const snowflakes = document.querySelectorAll('.snowflakes:before');
snowflakes.forEach((snowflake) => {
snowflake.style.left = `${Math.random() * window.innerWidth}px`;
snowflake.style.animationDelay = `${Math.random() * 5}s`;
});
```
这段代码会在页面背景上飘落雪花的效果,你可以根据需要自定义动画元素和样式。
阅读全文