我有以下 HTML:
<div id="tab1" style="position:relative; background-image:url(buttons/off.png);
<a href="javascript:ChangeBackgroundImageOfTab('tab1', 'on');">
<img id="DivBtn1" name="DivBtn1" src="buttons/text.png" >
</a>
</div>
和以下 Javascript:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.background-image= 'url("buttons/" + imagePrefix + ".png")';
}
当我尝试通过调用 getElementByID 设置选项卡背景图像时出现问题 - 我现在知道如何创建一个动态 URL,该 URL 使用传入的参数以及其他一些硬编码值。在这种情况下,我们将 OFF 背景图像与 ON 背景图像交换。
我该怎么做?有没有什么方法可以使用 javascript 变量,为其分配完整路径,然后将其作为背景图像路径发送到调用中?
最佳答案
您需要连接您的字符串。
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
按照您的方式,它只是制作 1 个长字符串,而不是实际解释 imagePrefix。
我什至建议单独创建字符串:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
正如下面 David Thomas 所提到的,您可以放弃字符串中的双引号。这是一篇小文章,可以更好地了解字符串和引号/双引号之间的关系:http://www.quirksmode.org/js/strings.html
关于Javascript-通过函数和函数参数设置 DIV 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665702/