使用javascript设置图像源和背景图像

aba*_*ter 3 javascript dom image background-image

我看了很多其他帖子,我想我正在使用建议的确切语法.但是,我没有让图像显示出来.我有一个jsfiddle.这是一个小问题吗?它也没有在我正在研究的网站上工作.

<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;
Run Code Online (Sandbox Code Playgroud)

Bub*_*les 10

两个小问题:

  1. getElementByID不是一个功能; getElementById是.

  2. 对于图像源和背景图像,URL的格式是不同的.试试这个: 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;