问题描述
我看过很多其他帖子,我想我使用的是完全符合语法的建议。但是,我没有看到图像出现。我有一个。这是一个jsfiddle问题吗?
I've looked at many other posts and I think I'm using the exact syntax suggested. However, I'm not getting the images to show up. I have a jsfiddle. Is it a jsfiddle issue? It's also not working on a website I'm working on.
<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src="http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg" />
var string = "url('http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;
推荐答案
两个小问题:
-
getElementByID
不是一个函数;getElementById
是。
getElementByID
is not a function;getElementById
is.
网址格式对于图片来源和背景图片是不同的。尝试这样:
var string ='';
document.getElementById(divtest)。style.backgroundImage =url('+ string +');
document.getElementById(imgtest)。src = string;
The format for a url is different for an image source and a background image. Try this:var string = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg';document.getElementById("divtest").style.backgroundImage = "url('" + string + "')";document.getElementById("imgtest").src = string;
这篇关于使用javascript设置图像源和背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!