显示来自提取 API 响应的图像,但它不会显示。我做错了什么?



const url = "https://api.rawg.io/api/games/4200";
async function createGameDetails() {
const heading = document.querySelector("h1");
try {
const response = await fetch(url);
const info = await response.json();

heading.innerHTML = info.name;
const image = document.querySelector(".image");
image.innerHTML = info.background_image;
const description = document.querySelector(".description");
description.innerHTML = info.description;
} catch (error) {
heading.innerHTML = "error.";
console.log(error);
}
}
createGameDetails();
.image {
height: 200px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/question3.css" />
</head>
<body>
<div class="container">
<h1>Name of game</h1>
<div
class="image"
style="background-image: url('https://via.placeholder.com/1000');"
></div>
<div class="description">Description goes here</div>
</div>
<script src="js/question3.js"></script>
</body>
</html>

我试图获取一个API响应,并将其显示在带有image类的imagediv中的background_image,但它不会显示。我做错了什么?我在这里发布JavaScript、CSS和HTML,以防有人看到。我将非常感谢任何可能有所帮助的答案。

您需要设置元素的背景图像样式,而不是innerHtml

const url = "https://api.rawg.io/api/games/4200";
async function createGameDetails() {
const heading = document.querySelector("h1");
try {
const response = await fetch(url);
const info = await response.json();
heading.innerHTML = info.name;
const image = document.querySelector(".image");

//changed this line
image.style.backgroundImage = `url(${info.background_image})`;
const description = document.querySelector(".description");
description.innerHTML = info.description;
} catch (error) {
heading.innerHTML = "error.";
console.log(error);
}
}
createGameDetails();
.image {
height: 200px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/question3.css" />
</head>
<body>
<div class="container">
<h1>Name of game</h1>
<div class="image" style="background-image: url('https://via.placeholder.com/1000');"></div>
<div class="description">Description goes here</div>
</div>
<script src="js/question3.js"></script>
</body>
</html>

相关内容

最新更新