我需要设置使用纯JavaScript(无JQuery的或其他的库)的背景图像。
我使用如下所示的JavaScript设置背景图像。 Firefox的控制台,检查电网和CSS引擎都表明,背景图像是理所应当的。我已经成功地设置背景颜色,显示出该元素是不是隐藏的,我没有选择错误的元素。正如下面的代码显示,我曾试图与透明度和背景颜色播放。这是徒劳的。将鼠标悬停在图片URL,火狐显示,图像实际上是正确加载。
下面是我的javascript:
var shadow = document.getElementById("shadow");
shadow.style.backgroundColor = "transparant";
shadow.style.opacity = "1";
shadow.style.backgroundImage = image;
CSS应用到元素在程序启动时
div#shadow
{
opacity: 0;
position: absolute;
top: 315px;
left: 721px;
width: 48px;
height: 48px;
}
元素只是一个DIV嵌套在<body>
内
<html>
<body>
<div id="shadow"></div>
</body>
</html>
拼写错误在透明的形象不只是名称的网址
var shadow = document.getElementById("shadow");
shadow.style.backgroundColor = "transparent";
shadow.style.opacity = "1";
shadow.style.backgroundImage = "url('image+address')";
div#shadow
{
opacity: 0;
position: absolute;
top: 315px;
left: 721px;
width: 48px;
height: 48px;
}
<html>
<body>
<div id="shadow"></div>
</body>
</html>
对于style.backgroundImage
属性,你需要一个图像路径,像"url('image.png')"
。否则,指定一个图像的URL变量image
。
你能提供你的“形象”变种?我换成你一个网址VAR和它工作得很好。
shadow.style.backgroundImage = "url('http://placehold.it/300x300')";
此外,尝试通过CSS,也许背景尺寸增加了一些背景属性。
你是太多了在这里做的方式。无需opacity
或transparent
或backgroundColor
。只需设置background
的形象。
但是,当你需要提供一个路径属性CSS,你需要通过使用url()
功能,你似乎没有做这条道路。
// Best practice: don't set individual properties on the
// style of an element. Add/remove pre-made classes.
document.querySelector("div").classList.add("background");
body { background-color:#e0e0e0; }
div { width:150px; height:150px; border:1px solid black; padding:10px;}
.background {
/* Just set the background property using url(path). That's it. */
background:url("http://www.thetherapystore.com.au/wp-content/uploads/2015/06/SSMILE.jpg");
background-size:contain; /* Only used here to scale the image to fit */
}
<div>This content is in the foreground.</div>