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

标签 jquery css image

我的 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/

相关文章:

css - 剪绳动画,纯CSS

r - 在 R 中,如何将 data.tree 图保存到文件中?

php - 将 php 结果与 jQuery 接口(interface)

javascript - CSS 和 JQuery 在 Ajax 调用后不起作用

css - 一个css问题,寻求帮助

css - 如何在 reactjs 中删除第三方 js 文件的特定 css 样式

javascript - Laravel 5.5 DataTables Yajra Ajax Crud

javascript - 带有复选框和彩色色板的 flot.js 绘图不起作用

python - 设置 Matplotlib 颜色条大小以匹配图形

C++ Builder 如何用 vector 构建动态对象?