我的 css 中有几个地方有条目,例如:
button {
background-image: url('../images/button.png');
}
我想要 jQuery 中的一个函数,它将所有 background-image
url 中所有出现的 images/
更改为如下内容:
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.Rule -- http://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 - 在启动时重新定位我的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886222/