所以我試圖從 unsplash api 制作影像的全屏背景,但是當我這樣做時我似乎無法更改 div 的背景影像 url document.getElementById("image").style.background = 'url("data["results"][0]["urls"]["regular"]")';。但是如果我不使用 div 而是使用 img ,它可以作業,但我不能讓它全屏顯示。任何人都知道對此有任何修復嗎?
這是我的代碼:
js
fetch("https://api.unsplash.com/search/photos?query=philippines&client_id=2BHRf_91BeuRTt7CDCE-_eA3l95wlZLWlyog-KQ2c2Y")
.then(
function(response){
console.log(response);
if(response.status !== 200){
console.log("There was a problem. Status code: " response.status);
return;
}
response.json().then(
function(data){
document.getElementById("image").style.background = 'url("data["results"][0]["urls"]["regular"]")';
}
)
}
)
.catch(
function(err){
console.log(err '404');
}
)
html
<html>
<head></head>
<link rel="stylesheet" href="style.css">
<body>
<!-- <div class = "image_container"> -->
<div id = "image"></div>
<!-- <img id="image"></img> -->
</div>
</body>
<script src="requests.js"></script>
</head>
</html>
css
*{
padding: 0;
margin: 0;
}
#image{
height: 100vh;
background-image: url();
background-size: cover;
background-repeat: no-repeat;
}
uj5u.com熱心網友回復:
你忘記了一些"在你的url().
這是一個例子:
fetch("https://api.unsplash.com/search/photos?query=philippines&client_id=2BHRf_91BeuRTt7CDCE-_eA3l95wlZLWlyog-KQ2c2Y")
.then(
function(response){
if(response.status !== 200){
console.log("There was a problem. Status code: " response.status);
return;
}
response.json().then(
function(data){
document.getElementById("image").style.background = 'url(' data["results"][0]["urls"]["regular"] ')';
}
)
}
)
.catch(
function(err){
console.log(err '404');
}
)
*{
padding: 0;
margin: 0;
}
#image{
height: 100vh;
background-size: cover !important;
background-repeat: no-repeat !important;
}
<div id = "image"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421438.html
標籤:
下一篇:請我使用fetch從API獲取資料,但只有JSX沒有產品回傳。Api來自:http://fakestoreapi.com/docs
