插入 javascript 变量作为背景图片源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19066638/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:13:47  来源:igfitidea点击:

Insert javascript variable as background image source

javascriptvariablesbackground-image

提问by Ian Dimmick

I have a variable that I can display on the page by using the following <script>document.write(image)</script>

我有一个变量,可以使用以下命令在页面上显示 <script>document.write(image)</script>

I can copy the result to the browser and it displays the file I require.

我可以将结果复制到浏览器并显示我需要的文件。

What I want to do is to take that variable and use it to specify the src of my background image

我想要做的是获取该变量并使用它来指定我的背景图像的 src

`<p style="background-image: url(**image**);">`

I know that this is probably simple to you guys, but I have spent the whole day and am losing a lot of hair over this one. Thanks for your time....

我知道这对你们来说可能很简单,但我已经花了一整天的时间并且为此掉了很多头发。谢谢你的时间....

回答by adeneo

If the element is selectable :

如果元素是可选的:

<p id="paragraph">Some text</p>

You can change the style with javascript:

您可以使用 javascript 更改样式:

document.getElementById('paragraph').style.background = 'url('+image+')';

if you're creating the paragraph you can do:

如果您正在创建段落,您可以执行以下操作:

var p = document.createElement('p');
p.style.background = 'url('+image+')';

回答by Nicolás Straub

Give the <p>element an id:

<p>元素一个id:

<p id="myPElement">

Manipulate it in the dom...

在 dom 中操作它...

document.getElementById('myPElement').style.backgroundImage = 'url(' + image + ')';

... or with jquery:

...或使用jquery:

$('#myPElement').css('background-image', 'url(' + image + ')');

回答by Ian Dimmick

I didn't give enough background in my original question...

我在最初的问题中没有提供足够的背景...

ie; I forgot to mention that I was attempting to do this in the middle of a server side loop.

IE; 我忘了提到我试图在服务器端循环的中间执行此操作。

I achived what I had set out to do with the following code

我用下面的代码实现了我的目标

`<script type="text/javascript">document.write("<table background=\"http://..../Pages/"+image+"/bkg.jpg\" >");`

Thank you VERY much for your help !!

非常感谢您的帮助 !!