要在网页上实现一个简单的天气预报功能,可以使用JavaScript结合一个天气API(例如OpenWeatherMap)来获取实时天气数据并展示在前端。以下是一个完整的示例,包括HTML、CSS和JavaScript代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>天气预报</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="weather-container">
<h1>天气预报</h1>
<input type="text" id="cityInput" placeholder="请输入城市名称">
<button id="getWeatherBtn">获取天气</button>
<div id="weatherResult"></div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
font-family: Arial, sans-serif;
background-color: #e0f7fa;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.weather-container {
background-color: #ffffff;
padding: 20px 30px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
text-align: center;
}
input[type="text"] {
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#weatherResult {
margin-top: 20px;
}
document.getElementById('getWeatherBtn').addEventListener('click', () => {
const city = document.getElementById('cityInput').value.trim();
if (city === "") {
alert("请输入城市名称!");
return;
}
// 替换为你的OpenWeatherMap API密钥
const apiKey = 'YOUR_API_KEY_HERE';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}&units=metric&lang=zh_cn`;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error("城市未找到或其他网络错误");
}
return response.json();
})
.then(data => {
const weatherDescription = data.weather[0].description;
const temperature = data.main.temp;
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
document.getElementById('weatherResult').innerHTML = `
<h2>${data.name} 的天气</h2>
<p><strong>描述:</strong> ${weatherDescription}</p>
<p><strong>温度:</strong> ${temperature} °C</p>
<p><strong>湿度:</strong> ${humidity}%</p>
<p><strong>风速:</strong> ${windSpeed} m/s</p>
`;
})
.catch(error => {
document.getElementById('weatherResult').innerHTML = `<p style="color:red;">${error.message}</p>`;
});
});
script.js
中的YOUR_API_KEY_HERE
替换为你获取的API密钥。index.html
、styles.css
和script.js
。index.html
,输入城市名称后点击“获取天气”按钮,即可显示该城市的实时天气信息。通过以上步骤,你可以实现一个基本的天气预报功能,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云