HTML、CSS和JavaScript实现简单天气预报

使用HTML、CSS和JavaScript实现简单天气预报的步骤:

  1. 首先需要获取天气API的数据,可以通过向第三方天气数据服务商发送HTTP请求来获取数据。例如,可以使用Yahoo Weather API或OpenWeatherMap API等。这里以OpenWeatherMap API为例,获取当前城市的天气情况。

  2. 接着,将获取到的天气数据动态地展示在HTML页面上。可以使用JavaScript的DOM操作方法,将获取到的数据渲染到页面上指定的位置。

  3. 最后,为了美化界面,可以使用CSS对整个天气预报页面进行样式设置。


 

下面是具体的代码实现:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>天气预报</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="weather">
      <span class="city"></span>
      <span class="temp"></span>
      <span class="description"></span>
      <img class="icon"/>
    </div>

    <script src="main.js"></script>
  </body>
</html>
.weather {
  width: 300px;
  height: 150px;
  background-color: #eee;
  border-radius: 10px;
  text-align: center;
  margin: 50px auto;
  padding: 20px;
}

.city {
  font-size: 25px;
  font-weight: bold;
  display: block;
  margin-bottom: 15px;
}

.temp {
  font-size: 18px;
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}

.description {
  font-size: 16px;
  display: block;
  margin-bottom: 15px;
}

.icon {
  width: 50px;
  height: auto;
  margin-top: 10px;
}
let city = "北京"; // 获取天气的城市
let apiKey = "your_api_key"; // 替换为你自己的API Key

let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&lang=zh_cn`;

fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data);

    let cityName = data.name;
    let temperature = Math.round(data.main.temp - 273.15);
    let description = data.weather[0].description;
    let iconCode = data.weather[0].icon;

    document.querySelector(".city").textContent = cityName;
    document.querySelector(".temp").textContent = `${temperature}°C`;
    document.querySelector(".description").textContent = description;
    document.querySelector(".icon").setAttribute("src", `http://openweathermap.org/img/w/${iconCode}.png`);
  })
  .catch(err => {
    console.log(err);
  });

 


上面的代码中,先定义了要获取天气数据的城市和API Key,在JavaScript中使用fetch方法发送HTTP请求,获取数据后再使用DOM操作将数据渲染到HTML页面上对应的元素中。

如果使用Vue.js框架开发,则可以更加简便地实现天气预报功能,具体步骤如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>天气预报</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="app">
    <div class="weather">
      <span class="city">{{ city }}</span>
      <span class="temp">{{ temperature }}°C</span>
      <span class="description">{{ description }}</span>
      <img :src="iconUrl"/>
    </div>
var app = new Vue({
  el: '#app',
  data: {
    city: "北京",
    apiKey: "your_api_key",
    temperature: "",
    description: "",
    iconCode: ""
  },
  methods: {
    getWeatherData: function() {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${this.apiKey}&lang=zh_cn`;

      fetch(url)
        .then(response => response.json())
        .then(data => {
          console.log(data);

          this.temperature = Math.round(data.main.temp - 273.15);
          this.description = data.weather[0].description;
          this.iconCode = data.weather[0].icon;
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  computed: {
    iconUrl: function() {
      return `http://openweathermap.org/img/w/${this.iconCode}.png`;
    }
  },
  mounted: function() {
    this.getWeatherData();
  }
});

在上面的代码中,我们使用了Vue.js的data属性来存储需要展示的数据和API Key信息。通过Vue.js的methods属性定义一个获取天气数据的方法,并通过computed属性计算图片地址,最后使用mounted属性在页面加载时自动调用获取天气数据的方法。

  • 3
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个简单的示例代码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` 参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值