[英]How to change background image according to result from an api?
更改背景图像的功能:
function backgroundChange(checkDay) {
if (checkDay === 0) {
document.body.style.backgroundImage = "url('night.jpg')";
} else if (checkDay === 1) {
document.body.style.backgroundImage = "url('day.jpg')";
}
}
从 api 获取结果的函数
使用的 api 是: https ://rapidapi.com/weatherapi/api/weatherapi-com/ 我直接从上面的链接使用了 axios(js) 的实时天气 api 功能
const options = {
method: "GET",
url: "https://weatherapi-com.p.rapidapi.com/current.json",
params: { q: "Los angeles" },
headers: {
"X-RapidAPI-Key": "API_KEY",
"X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
}
};
var checkDay;
axios
.request(options)
.then(function (response) {
console.log("-->", response.data.current.is_day);
checkDay = response.data.current.is_day;
console.log(checkDay);
})
.catch(function (error) {
console.error(error);
});
您提供的相同代码对我有用。 请检查您是否有一些组件(和附加的样式)设置完全重叠主体。
这是我尝试过的,只需更改 API_key 即可:
function getWeatherInfo() { var location = document.getElementById("location").value; var options = { method: "GET", url: "https://weatherapi-com.p.rapidapi.com/current.json", params: { q: location }, headers: { "X-RapidAPI-Key": "API_Key", "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com", }, }; console.log(options); var checkDay; axios .request(options) .then(function (response) { console.log("-->", response.data.current.is_day); checkDay = response.data.current.is_day; console.log(checkDay); document.getElementById("results").innerHTML = JSON.stringify(response); if (checkDay === 0) { document.body.style.backgroundImage = "url('night.jpg')"; } else if (checkDay === 1) { document.body.style.backgroundImage = "url('day.jpg')"; } }) .catch(function (error) { console.error(error); }); }
body{ background-color: lightseagreen; } #results{ height:600px; width:100%; background-color: white; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="getWeather.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <h1>Weather</h1> <input id="location" type="text" value="Los Angeles" placeholder="enter location here"> <button onclick="getWeatherInfo()">Get Weather Info</button> <main> <code id="results"></code> </main> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.