使用javascript设置图像源和背景图像
我看过许多其他帖子,我想我使用的是建议的确切语法。但是,我不会让图像显示出来。我有一本书。这是一个复杂的问题吗?它也不适用于我正在开发的网站使用javascript设置图像源和背景图像,javascript,image,dom,background-image,Javascript,Image,Dom,Background Image,我看过许多其他帖子,我想我使用的是建议的确切语法。但是,我不会让图像显示出来。我有一本书。这是一个复杂的问题吗?它也不适用于我正在开发的网站 <div id="divtest">Hello</div> <img id="imgtest" /> <img id="imgreal" src="http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg" /> var stri
<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;
你好
var string=“url('http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg')";
警报(字符串)
document.getElementByID(“divtest”).style.backgroundImage=string;
document.getElementByID(“imgtest”).src=string;
两个小问题:
getElementByID
不是一个函数getElementById
var字符串=“”;
document.getElementById(“divtest”).style.backgroundImage=“url(““+string+”)”);
document.getElementById(“imgtest”).src=string;
将
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;
希望这有帮助可能是因为图像不存在?否则就可以了。看起来像是JSFIDLE问题。JS是区分大小写的:
document.getElementByID
!=document.getElementByID
。你的一样好,但当我向下滚动时气泡是第一个。谢谢!