简体   繁体   中英

change css background of all elements on a page

I want to change the background image of every element on a page by adding a string to it's address in this manner:

Get the back ground image address of an element from the styles:

background-image: url("img/sprites.png");

Add the string ?ver=3 to it, so it will become like this

background-image: url("img/sprites.png?ver=3");

I guess I may do that on a single known element by somthing like this:

document.getElementById('elementId').style.backgroundImage += "?ver=3"

Am I right?

However, I want to do this to all the elements. How can I have the loop access all the elements?

You could try using jquery.

$("*").css('backgroundImage', $(this).css('backgroundImage')+'?ver=3');

I just typed this from memory so it might not be 100% but it seems like it would work.

Possibly this:

$("*").each(function(){$(this).css('backgroundImage', $(this).css('backgroundImage')+'?ver=3');});

Hope this help a little.

You could use document.getElementsByTagName :

var elms = document.getElementsByTagName('*');
for (var i = 0, len = elms.length; i != len; ++i) {
  elms[i].style.backgroundImage += '?ver=3';
}

Or, you could use the DOM to modify the stylesheet object directly. You'd have to write separate codepaths for different browsers, but it would probably run much faster.

maybe something like this with jquery:

$('*').each(function(){
$(this).css( 'background-image', $(this).css('background-image') + "?ver=3");
});

I would prefer to use $('body *') in the selector to not include elements like head and html.

suppose the elements that you want to assign a background to are wrapped in a div with class 'mysprites':

<div id="mysprites">
    <div></div>
    <div></div>
    <div></div>
</div>

To let each sprites.png version number correspond to the i-th element, just call

$('#mysprites').each(function(index) {
$(this).css("background-image", "url(img/sprites.png?ver=" + index + ")");
})

like in this fiddle

(if you don't know jquery, just download it and add it to the header of your html file like:

<script language="javascript" type="text/javascript" src="jquery.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM