繁体   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