写一个html+css+js的天气预报代码
时间: 2023-10-04 14:12:29 浏览: 61
好的,以下是一个简单的示例代码:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>天气预报</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>天气预报</h1>
<div class="weather-info">
<div class="location">
<h2>北京</h2>
<p>2021年7月21日 星期三</p>
</div>
<div class="temperature">
<h2>28℃</h2>
<p>多云转晴</p>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS代码:
```
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.container {
max-width: 800px;
margin: 0 auto;
text-align: center;
padding: 20px;
}
.weather-info {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 50px;
}
.location {
flex-grow: 1;
margin-right: 20px;
}
.temperature {
flex-grow: 1;
margin-left: 20px;
}
h1 {
text-align: center;
font-size: 48px;
margin-bottom: 50px;
}
h2 {
font-size: 36px;
margin-bottom: 10px;
}
p {
font-size: 24px;
margin: 0;
}
```
JavaScript代码:
```
// 用于获取天气信息的API地址
const weatherApiUrl = "https://api.openweathermap.org/data/2.5/weather?q=北京&appid=YOUR_APP_ID&units=metric";
// 获取天气信息并更新页面
fetch(weatherApiUrl)
.then(response => response.json())
.then(data => {
const location = document.querySelector(".location h2");
const date = new Date(data.dt * 1000);
const temperature = document.querySelector(".temperature h2");
const description = document.querySelector(".temperature p");
location.textContent = data.name;
dateString = date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
dateElement = document.createElement("p");
dateElement.textContent = dateString;
location.appendChild(dateElement);
temperature.textContent = `${data.main.temp}℃`;
description.textContent = data.weather[0].description;
})
.catch(error => console.error(error));
```
请注意,这个示例代码中的 `YOUR_APP_ID` 需要替换为你自己的 OpenWeatherMap API Key。此外,这个示例代码只获取了北京的天气信息,如果需要获取其他城市的天气信息,需要修改 `weatherApiUrl` 中的 `q` 参数。