在 JavaScript 中设置 <div> 的背景图片

Set background-image of <div> in JavaScript

我正在尝试在 Javascript 中设置 <div>background-image 属性,但图像不会出现。高度是100px,可以看到下面的内容被压下去了,但是这里没有图片

这是我的代码:

var bg = document.createElement("div");

$.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function(data) {
    bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg");';
    bg.style.height = "100px";
    statsDiv.appendChild(bg);
    //some other stuff that uses the JSON that doesn't matter
});

我知道 <div> 那里 ,因为它显示了元素之间的 100px 间隙,但没有图像,并且 $.getJSON() 有效.

解法:

我只需要删除分号:

之前: bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg");';

之后: bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg")';

这对我有用:

const statsDiv = $('.statsDiv');

statsDiv.append('<div class="bgdiv"></div>');
const bg = $(".bgdiv");

const bgimageURL = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg")';

$.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function(data) {
    bg.css({
      'background-image': bgimageURL,
      'height': '100px'
    });
    statsDiv.append(bg);
    
    // ...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="statsDiv">This is statsDiv</div>

(编辑:我原来的答案不正确。我修正了它)

到目前为止看起来不错。新的 div 必须附加到 DOM.

$.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function() {
    console.log("success");

    var bg = document.createElement("div");
    document.body.appendChild(bg);
    bg.style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg')";

    bg.style.height = "100px";

  })
  .done(function() {
    console.log("second success");
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("complete");
  });
div {
  border: 1px solid red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>