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

3

我查看了许多其他帖子,认为我正在使用建议的确切语法。然而,我的图片没有显示出来。我有一个jsfiddle。这是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;

可能是因为图片不存在?否则就没问题了。看起来像是jsfiddle的问题。 - putvande
2
JS 是大小写敏感的:document.getElementByID !== document.getElementById - Teemu
2个回答

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;

3
请将getElementByID改为getElementById,你的代码中还存在另一个错误:
你写道:
var string = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";

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

但是src不需要url(,所以你应该写成:
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;

希望这能帮到你。

1
你的也很好,但是当我向下滚动时,Bubbles在第一位。谢谢! - abalter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接