Html 通过函数和函数参数设置 DIV 的 Javascript 背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18665702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript-Setting background image of a DIV via a function and function parameter
提问by jordan
I have the following HTML:
我有以下 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>
and the following Javascript:
以及以下 Javascript:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.background-image= 'url("buttons/" + imagePrefix + ".png")';
}
The issue arises when i try to set the tabs background image via a call to getElementByID - I do now know how to create a dynamic URL that uses the parameter that was passed in, along with some other hard coded values. In this case, we are swapping the OFF background image with the ON background image.
当我尝试通过调用 getElementByID 设置选项卡背景图像时出现问题 - 我现在知道如何创建一个动态 URL,该 URL 使用传入的参数以及其他一些硬编码值。在这种情况下,我们将 OFF 背景图像与 ON 背景图像交换。
How can i do this? Is there some way to use a javascript variable, assign the full path to it, then send it into the call as the background image path?
我怎样才能做到这一点?有没有办法使用javascript变量,为其分配完整路径,然后将其作为背景图像路径发送到调用中?
回答by TyMayn
You need to concatenate your string.
您需要连接字符串。
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
您拥有它的方式,它只是制作 1 个长字符串,而不是实际解释 imagePrefix。
I would even suggest creating the string separate:
我什至建议单独创建字符串:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
正如下面 David Thomas 所提到的,您可以在字符串中去掉双引号。这是一篇小文章,可以更好地了解字符串和引号/双引号之间的关系:http: //www.quirksmode.org/js/strings.html
回答by moritzpflaum
From what I know, the correct syntax is:
据我所知,正确的语法是:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}
So basically, getElementById(tabName).backgroundImage
and split the string like:
所以基本上,getElementById(tabName).backgroundImage
并将字符串拆分为:
"cssInHere('and" + javascriptOutHere + "/cssAgain')";