css制作web天气
使用CSS制作Web天气效果
通过CSS可以创建动态的天气效果,如晴天、雨天、雪天等。以下是几种常见天气效果的实现方法。
晴天效果
创建一个太阳和云朵的简单组合,使用CSS动画让太阳旋转。
<div class="weather sunny">
<div class="sun"></div>
<div class="cloud"></div>
</div>
.weather {
width: 200px;
height: 200px;
position: relative;
background: skyblue;
}
.sun {
width: 50px;
height: 50px;
background: yellow;
border-radius: 50%;
position: absolute;
top: 20px;
left: 20px;
animation: rotate 5s linear infinite;
}
.cloud {
width: 80px;
height: 30px;
background: white;
border-radius: 20px;
position: absolute;
top: 50px;
left: 60px;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
雨天效果
使用伪元素和动画模拟雨滴下落。
<div class="weather rainy">
<div class="cloud"></div>
</div>
.rainy {
background: darkgray;
}
.rainy .cloud {
width: 100px;
height: 40px;
background: white;
border-radius: 20px;
position: absolute;
top: 30px;
left: 50px;
}
.rainy .cloud::after {
content: '';
position: absolute;
width: 2px;
height: 10px;
background: lightblue;
top: 40px;
left: 10px;
animation: rain 1s linear infinite;
}
@keyframes rain {
from { transform: translateY(0); }
to { transform: translateY(50px); }
}
雪天效果
使用多个动画元素模拟雪花飘落。
<div class="weather snowy">
<div class="cloud"></div>
</div>
.snowy {
background: lightgray;
}
.snowy .cloud {
width: 100px;
height: 40px;
background: white;
border-radius: 20px;
position: absolute;
top: 30px;
left: 50px;
}
.snowy .cloud::after {
content: '❄';
position: absolute;
font-size: 10px;
top: 40px;
left: 10px;
animation: snow 3s linear infinite;
}
@keyframes snow {
from { transform: translateY(0) rotate(0deg); }
to { transform: translateY(50px) rotate(360deg); }
}
动态切换天气
通过JavaScript动态切换天气效果。

<div class="weather" id="weather">
<div class="sun"></div>
<div class="cloud"></div>
</div>
<button onclick="changeWeather('sunny')">Sunny</button>
<button onclick="changeWeather('rainy')">Rainy</button>
<button onclick="changeWeather('snowy')">Snowy</button>
function changeWeather(type) {
const weather = document.getElementById('weather');
weather.className = 'weather ' + type;
}
以上方法展示了如何使用CSS和少量JavaScript创建动态的天气效果。可以根据需求进一步调整样式和动画参数。






