Javascript-通过函数和函数参数设置DIV的背景图像 [英] Javascript-Setting background image of a DIV via a function and function parameter

查看:242
本文介绍了Javascript-通过函数和函数参数设置DIV的背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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:

and the following Javascript:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    document.getElementById(tabName).style.background-image= 'url("buttons/" + imagePrefix + ".png")';
}

当我尝试通过调用getElementByID设置标签背景图片时出现问题 - 我现在知道如何创建动态网址使用传入的参数以及其他一些硬编码值,在这种情况下,我们将使用ON背景图像交换OFF背景图像。

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.

如何我有这样做吗?有一些方法可以使用一个javascript变量,分配完整的路径,然后将其作为背景图像路径发送到调用

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?

推荐答案

您需要连接字符串。

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

你的方式,它只是使1个长字符串,而不是实际上解释imagePrefix。

The way you had it, it's just making 1 long string and not actually interpreting 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;
}

正如David Thomas下面提到的,你可以把你的字符串中的双引号。这里有一篇文章,可以更好地了解字符串和引号/双引号的关系: http://www.quirksmode .org / js / strings.html

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

这篇关于Javascript-通过函数和函数参数设置DIV的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆