最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Set image source and background image with javascript - Stack Overflow

programmeradmin1浏览0评论

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=".jpeg" />

var string = "url('.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;

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;
Share Improve this question asked Nov 18, 2013 at 18:53 abalterabalter 10.4k18 gold badges98 silver badges166 bronze badges 2
  • Maybe because the image doesn't exist? Otherwise it is fine. Looks like a jsfiddle issue. – putvande Commented Nov 18, 2013 at 18:56
  • 2 JS is case-sensitive: document.getElementByID !== document.getElementById. – Teemu Commented Nov 18, 2013 at 18:58
Add a comment  | 

2 Answers 2

Reset to default 10

Two minor problems:

  1. getElementByID is not a function; getElementById is.

  2. 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;

Replace getElementByID by getElementById and there is another error in your code:

you write:

var string = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";

document.getElementById("imgtest").src = string;

But src doesn't need url(, so you should write :

var str1 = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";
document.getElementById("divtest").style.backgroundImage = str1 ;

var str2 = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg';
document.getElementById("imgtest").src = str2;

Hope this helps

发布评论

评论列表(0)

  1. 暂无评论