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

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

问题描述

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

以及以下 Javascript:

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

当我尝试通过调用 getElementByID 设置选项卡背景图像时出现问题 - 我现在知道如何创建一个动态 URL,该 URL 使用传入的参数以及其他一些硬编码值.在这种情况下,我们将关闭背景图像与开启背景图像交换.

我该怎么做?有没有办法使用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

I have the following 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:

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.

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?

解决方案

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.

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

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

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