21xrx.com
2025-03-23 13:29:14 Sunday
文章检索 我的文章 写文章
用JavaScript打造一个手机天气预报应用
2023-06-12 09:12:23 深夜i     --     --
JavaScript 手机 天气预报

文章:

作为现代人,我们无时无刻不关注着天气预报,但是在手机应用上翻来覆去也很不方便。这时候,一个简单的手机天气预报应用就能解决这个问题。那么,下面我们就用JavaScript来打造一个手机天气预报应用。

首先,我们需要调用一个天气API来获取天气信息。我们用OpenWeatherMap API,使用方法如下:

script
fetch('https://api.openweathermap.org/data/2.5/weather?q=london&appid=API_KEY')
 .then(response => response.json())
 .then(data => console.log(data));

其中,'https://api.openweathermap.org/data/2.5/weather'是API的URL,'?q=london'表示查询伦敦的天气,'&appid=API_KEY'是用于授权访问的API Key。需要注意的是,我们需要替换API_KEY为我们自己的API Key才能使用该API。

接下来,我们可以将获取的天气信息展示在手机应用上。我们可以用HTML和CSS构建页面,然后用JavaScript来填充内容。具体实现如下:

ss
#weather-app
 display: flex;
 flex-direction: column;
 align-items: center;
 margin-top: 20px;
.weather-icon
 font-size: 64px;
 margin-bottom: 20px;
.temperature
 font-size: 48px;
 font-weight: bold;
.description
 font-size: 24px;

script
const apiKey = 'YOUR_API_KEY';
const city = 'london';
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
 .then(response => response.json())
 .then(data => {
  const iconId = data.weather[0].icon;
  const temperature = Math.round(data.main.temp - 273.15);
  const description = data.weather[0].description;
  const weatherApp = document.getElementById('weather-app');
  const weatherIcon = weatherApp.querySelector('.weather-icon');
  const temperatureElement = weatherApp.querySelector('.temperature');
  const descriptionElement = weatherApp.querySelector('.description');
  const iconUrl = `http://openweathermap.org/img/w/${iconId}.png`;
  weatherIcon.innerHTML = ``;
  temperatureElement.innerHTML = `${temperature}°C`;
  descriptionElement.innerHTML = description;
 });

这样,我们就可以用JavaScript打造出一个简单的手机天气预报应用了。

  
  

评论区