簡體   English   中英

如何使用 unsplash api 圖像設置 div 的背景圖像?

[英]How to set background image of div using an unsplash api image?

因此,我試圖從 unsplash api 制作圖像的全屏背景,但當我執行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;
}

您在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM