Set image source and background image with javascr

2019-07-04 02:47发布

问题:

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;

回答1:

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;



回答2:

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