JS实现动态天气预报页面
为了在HTML页面上显示天气预报,我们可以使用JS代码与天气API进行交互,获取实时的天气信息并动态展示。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Weather Forecast</title>
<style>
.weather-container {
text-align: center;
padding: 20px;
}
.weather {
font-size: 24px;
}
</style>
</head>
<body>
Today's Weather
[removed]
const apiKey = 'YOUR_API_KEY';
const city = 'Beijing';
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
.then(response => response.json())
.then(data => {
const weatherDescription = data.weather[0].description;
document.getElementById('weather').innerText = `Current weather in ${city}: ${weatherDescription}`;
})
.catch(error => console.error('Error fetching the weather data:', error));
[removed]
</body>
</html>
JS代码可以通过调用外部API(如OpenWeatherMap),动态获取指定城市的天气信息并展示在HTML页面中。这个示例中使用了fetch
方法来请求API,并将返回的数据在页面上进行展示。只需替换API密钥和城市名称,即可显示不同城市的天气情况。
1.09KB
文件大小:
评论区