如何将backgroundimage属性设置为RESTAPI中的url?

fcy6dtqo  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(413)

我正在尝试访问rest api,以访问其中的图像url。character.crative具有url,并已成功打印。但是当我试图改变的时候 document.getElementById('portrait').style.backgroundImage 它返回一个空字符串。我只想将背景图像设置为json中此url处的图像。
这也是我在这里的第一个问题,所以如果很难阅读,我很抱歉。
js-

  1. //Set the URL up. userKey will eventually be provided by a person. Using my own character for testing.//
  2. const url = "https://xivapi.com/character/";
  3. var userKey = "1814929"
  4. var api_url = url + userKey;
  5. console.log(api_url)
  6. //This calls the function below to access the API//
  7. getCharacter();
  8. //This is the function that gets access to the API. //
  9. async function getCharacter() {
  10. const response = await fetch(api_url);
  11. const character = await response.json();
  12. //This is where I'm having difficulty.
  13. //This does *NOT* change the backgroundImage property.
  14. document.getElementById('portrait').style.backgroundImage = character.Character.Portrait;
  15. console.log(document.getElementById('portrait').style.backgroundImage);
  16. //This accurately prints the Avatar's URL
  17. console.log(character.Character.Avatar);
  18. //This accurately prints the Portrait URL.
  19. console.log(character.Character.Portrait);
  20. }

html

  1. <body>
  2. ...
  3. <main>
  4. <h1 id="pageTitle">Main</h1>
  5. <div id="content">
  6. <div id="character">
  7. <div id="portrait">
  8. </div>
  9. </div>
  10. </div>
  11. </main>
  12. <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  13. <script src="/pages/scripts/main.js"></script>
  14. </body>
  15. </html>
5sxhfpxr

5sxhfpxr1#

css背景图像值的格式应为: url(site.com/someimage.png) 您缺少url Package 器。

相关问题