最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Insert javascript variable as background image source - Stack Overflow

programmeradmin1浏览0评论

I have a variable that I can display on the page by using the following <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

`<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....

I have a variable that I can display on the page by using the following <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

`<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....

Share Improve this question edited Sep 28, 2013 at 12:13 Steve Benett 12.9k7 gold badges61 silver badges81 bronze badges asked Sep 28, 2013 at 11:54 Ian DimmickIan Dimmick 731 gold badge1 silver badge3 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

If the element is selectable :

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

You can change the style with 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+')';

Give the <p> element an id:

<p id="myPElement">

Manipulate it in the dom...

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

... or with jquery:

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

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.

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 !!

发布评论

评论列表(0)

  1. 暂无评论