在启动时重新定位我的图像

在我的css的几个地方,我有以下条目:

button { background-image: url('../images/button.png'); } 

我想在jQuery中使用一个函数来将所有出现的images/在所有background-imageurl中更改为:

 button { background-image: url('../images/Customer/button.png'); } 

我目前用这段可怕的代码来做这件事,但我怀疑使用jQuery有一个更简洁的方法。 请注意,图像的实际位置保存在sessionStorage

 // Hacks all CSS styles that refer to the images folder. for ( s = 0; s < document.styleSheets.length; s++ ) { var mysheet=document.styleSheets[s]; var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules; // Look for: background-image: url(images/button.png); for (i=0; i < myrules.length; i++){ var css = myrules[i].style.cssText; if(css.indexOf('images/') != -1 ){ // Surgery on the cssText because the individual entries are read only. // Replace the css. myrules[i].style.cssText = css.replace("images/", sessionStorage.images); // That's the new style. } } } 

将此插件与jQuery一起使用:

jQuery.Rulehttp://flesler-plugins.googlecode.com/files/jquery.rule-1.0.2-min.js

然后执行以下操作:

 $(function(){ var customer = 'Oscar'; // Get all stylesheets $.rule().sheets.map(function(index, cssSheet){ // Get all css rules from all the stylesheets $.each(cssSheet.cssRules, function(index, cssRule){ // If cssRule is 'background-image' type if(cssRule.cssText.indexOf('background-image') != -1){ // Prepare new cssRule adding the customer var newCssRule = cssRule.cssText.replace('/images/', '/images/' + customer + '/'); // Add new cssRule to the correct stylesheet $.rule(newCssRule).appendTo('style'); } }); }); }); 

只是要知道,你可以用这个做更多的事情,看看这个链接:

http://flesler.webs.com/jQuery.Rule/

希望这可以帮助 :-)

你不应该在这里需要jQuery。

尝试为button引入新的CSS定义并将其添加到页面。 这将覆盖您之前的定义。

 var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = 'button { background-image: url("../images/Customer/button.png"); }'; document.head.appendChild(style); 

或者,调整button元素的内联CSS:

 var buttons = document.getElementsByTagName('button'), i = 0; for (; i < buttons.length; i++) { buttons[i].style.backgroundImage = 'url("../images/Customer/button.png")'; }