如何根据API结果值更改HTML背景?

问题描述 投票:0回答:2

我创建了带有openweathermap API的HTML,CSS,JS(不是jqurey)Web应用程序。我想根据天气改变背景。

但是我已经尝试了很多,但是没有用。 js文件是一个main.js文件。

这是JS代码。

function displayResults(weather) {
  var city = document.querySelector(".city");
  city.innerHTML = weather.name + ", " + weather.sys.country;

  let now = new Date();
  let date = document.querySelector(".location .date");
  date.innerHTML = dateBuilder(now);

  let temp = document.querySelector(".current .temp");
  temp.innerHTML = Math.round(weather.main.temp - ChangeTemp).toFixed(0) + "°C";

  var weather_el = document.querySelector(".current .weather");
  weather_el.innerHTML = weather.weather[0].main;
  var weatherinfo = weather.weather[0].main;

  let hilow = document.querySelector(".hi-low");
  hilow.innerText =
    "Low and High Temp: " +
    Math.round(weather.main.temp_min - ChangeTemp) +
    " °C / " +
    Math.round(weather.main.temp_max - ChangeTemp) +
    " °C";
}

function backgroundChange(weather) {
  var imgs = document.getElementById("allbody");

  imgs.style.backgroundImage = "url(background.gif)";

  if (weatherinfo == Rain) {
    imgs.style.backgroundImage = "url(rain3.gif)";
  } else if (weatherinfo == Clouds) {
    imgs.style.backgroundImage = "url(cloud.gif)";
  } else if (weatherinfo == Clear) {
    imgs.style.backgroundImage = "url(sky3.gif)";
  } else {
    imgs.style.backgroundImage = "url(background.gif)";
  }
}

不是工作功能backgroundchange。

这是HTML代码。

<div id='allbody' class="app" style="background-image: url(background.gif);">

<div>
    <header>
        <input type="text" autocomplete="off" class="search-box" placeholder="Please enter the location."/>

    </header>

    <main>
        <section class="location">
            <div class="city">Location, Country</div>
            <div class="date">Today date info</div>
        </section>
        <div class="current">
            <div class="temp"><span>Temp (°C)</span></div>
            <div id="wdata" class="weather">Weather</div>
            <div class="hi-low">Low and High Temp</div>
        </div>
...

如何根据天气改变背景图像?

谢谢

javascript html background-image weather openweathermap
2个回答
0
投票

代替imgs.style.backgroundImage = 'url(rain3.gif)';,也请尝试在图像路径周围用引号引起来的imgs.style.backgroundImage = 'url('rain3.gif')';


0
投票

而不是创建'imgs'变量,而是更好地使用;document.body.style.backgroundImage =“ url(background.gif)”;

function backgroundChange(weather) {
  if (weatherinfo == Rain) {
  document.body.style.backgroundImage = "url(rain3.gif)";
  } else if (weatherinfo == Clouds) {
  document.body.style.backgroundImage = "url(cloud.gif)";
  } else if (weatherinfo == Clear) {
  document.body.style.backgroundImage = "url(sky3.gif)";
  } else {
  document.body.style.backgroundImage= "url(background.gif)";
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.