【问题标题】:Relocate my images at startup在启动时重新定位我的图像
【发布时间】:2012-08-10 02:00:56
【问题描述】:

我在我的 css 中的几个地方都有条目,例如:

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

我想要 jQuery 中的一个函数,它将所有 images/ 在所有 background-image 网址中的所有出现更改为:

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 css image


    【解决方案1】:

    将此插件与 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/

    希望这会有所帮助:-)

    【讨论】:

    • 看起来不错。我不只是想要../Images/Customer/button.png,我想要在all urls 在all background-image所有 出现images/ all css 中的条目更改为包含客户名称。
    • 一个主要的一个和另外三个是特定于组件的。随着系统的发展,我期待更多。
    【解决方案2】:

    你不应该在这里需要 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")';
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      相关资源
      最近更新 更多