简体   繁体   English

Javascript element.style.backgroundImage无法加载图像

[英]Javascript element.style.backgroundImage not loading image

Not sure what I'm missing here... 不确定我在这里缺少什么...

window.onload = function() {
    var testDiv = document.createElement("div");
    testDiv.style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png')";

    document.body.appendChild(testDiv);
}

The issue is you're setting a background-image on a div with no height or width . 问题是您要在没有heightwidth的div上设置background-image Add those: 添加这些:

window.onload = function() {
    var testDiv = document.createElement("div");
    testDiv.style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png')";
    testDiv.style.backgroundSize="cover"; //image is large, you dont need this if you dont want
    testDiv.style.height="100px"; //add some value
    testDiv.style.width="100px"; //add some value

    document.body.appendChild(testDiv);
}

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM