【问题标题】:Replacing Specific color code in css using jquery使用 jquery 替换 css 中的特定颜色代码
【发布时间】:2015-08-23 17:56:51
【问题描述】:

我想将 #789034 代码替换为另一个代码,例如 #456780,它使用 jquery 在 main.css 中找到

我有一个 main.css 文件,如下所示:

.common-color
{
  color:#789034;
}

.new-cls
{
  border-color:#789034;
  height:300px;
}

.awesome-one
{
  background-color:#789034;
  height:200px;
  width:300px;
}

我想将 #789034 代码替换为另一个代码,例如 #456780,它使用 jquery 在 main.css 中找到,例如:

$(each where code=#789034)
{
  set code: #456780;
}

【问题讨论】:

  • 也许您应该有一个具有color: #789034; 的类,并将该类添加到需要此颜色的所有元素中。然后使用 jQuery 更改颜色会很容易:$('.myClass').css('color', '#456780');
  • 它实际上是不可能的,因为我在服务器属性上使用它,比如边框颜色:#789034- 认为我为代码创建了一个通用颜色类,如何传递该类作为边框颜色-像 1px solid-- .comon-color.
  • 是什么意思??实际上,我明确表示我想使用 jquery 一次性将所有地方的特定颜色代码替换为其他颜色代码-您的代码选择属性,我只想将代码代码替换为新颜色代码
  • 真的很抱歉,如果我粗鲁 - 那不是我的意图,真的很抱歉,是的,我很接近,非常感谢,只是它有额外的东西,即属性,我不想要属性作为参数。
  • stackoverflow.com/questions/27084411/… 的可能重复项(也没有公认的答案)

标签: jquery css html twitter-bootstrap


【解决方案1】:

您可以通过使用 CSS 变量来实现此功能。在 main.css 文件中定义一个变量。

:root {   
    --color1: #789034; 
}

并使用此变量代替颜色代码。

.common-color
{
  color: var(--color1);
}

现在您可以通过在参数中传递新颜色来实现以下功能来更改颜色。

function ChangeColor1(newColor)
{
  document.documentElement.style.setProperty('--color1',newColor);
}

【讨论】:

  • 这对我来说是最好和一致的答案。事实上,它避免了其他方法的许多错误。
【解决方案2】:

您可能想尝试以下方法:

将您的样式表内联到文档中,并由样式标签包裹:

<style id="myStyles" type="text/css"> /* all your css here */ </style>

现在你大概可以通过

得到这个的所有内容了
let myCss = document.getElementById('myStyles').innerHTML;

然后继续做替换魔法:

myCSS = myCSS.replace(/#789034/g, "#456780");

最后,充满希望地把它放回 DOM:

document.getElementById('myStyles').innerHTML = myCss;

但即使这应该可行,在我看来你很可能会带来XY problem

【讨论】:

    【解决方案3】:

    这是一个解决方案,我将逐步解释。

    首先,致电colorReplace("#789034", "#456780");。第一个值是目标颜色,第二个是替换颜色。

    在其中,$('*').map(function(i, el) { 将选择 DOM 树中的所有标签。对于每个元素,返回其getComputedStyle(el) 样式数组。您可以自定义选择器以加快处理速度(例如$('div').map(function(i, el)) {)。

    所有包含“颜色”的样式属性(例如background-color-moz-outline-color等),将检查颜色值是否等于您的目标颜色。如果是这样,它将被替换为目标颜色。

    返回的颜色类似于rgba(0,0,0,0)rgb(0,0,0),而不是#FFFFFF,因此可以快速将RGB 转换为十六进制以进行比较。这使用了内部的rgb2hex() 函数。

    我希望这就是你要找的。​​p>


    function colorReplace(findHexColor, replaceWith) {
      // Convert rgb color strings to hex
      // REF: https://stackoverflow.com/a/3627747/1938889
      function rgb2hex(rgb) {
        if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
          return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
      }
    
      // Select and run a map function on every tag
      $('*').map(function(i, el) {
        // Get the computed styles of each tag
        var styles = window.getComputedStyle(el);
    
        // Go through each computed style and search for "color"
        Object.keys(styles).reduce(function(acc, k) {
          var name = styles[k];
          var value = styles.getPropertyValue(name);
          if (value !== null && name.indexOf("color") >= 0) {
            // Convert the rgb color to hex and compare with the target color
            if (value.indexOf("rgb(") >= 0 && rgb2hex(value) === findHexColor) {
              // Replace the color on this found color attribute
              $(el).css(name, replaceWith);
            }
          }
        });
      });
    }
    
    // Call like this for each color attribute you want to replace
    colorReplace("#789034", "#456780");
    .common-color {
      color: #789034;
    }
    .new-cls {
      border-color: #789034;
      border-width: 4px;
      border-style: solid;
    }
    .awesome-one {
      background-color: #789034;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="common-color">color</div>
    <div class="new-cls">border-color</div>
    <div class="awesome-one">background-color</div>

    【讨论】:

    • 从哪里获取 CSS 规则? getComputedStyle?
    • 是的,getComputedStyle 将返回一个令人印象深刻的计算样式数组。此解决方案过滤那些包含“颜色”的样式,然后执行比较,并在需要时替换颜色
    • @Drakes 如果 css 看起来像颜色,如何替换:#efefef !important;
    • 您可能有兴趣知道(4 年后)这个答案是 discussed on meta
    • @Icepickle 感谢您的提醒
    【解决方案4】:

    为什么,它是初级的,亲爱的华生。只需获取所有可能的样式键,检查它们是否包含单词颜色,然后使用复杂的正则表达式系统将所有出现的颜色替换为新的颜色。

    // gathers all style "keys" like height, width, color, etc
    var keys = Object.values(window.getComputedStyle($('html').get(0)));
    // removes any style keys which are not color related
    var filteredKeys = keys.filter(function (key){return key.indexOf('color') > -1});
    // parses the hex string of the color to be replaced into its R, G, and B parts and stores them in an array
    var colors = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec("#789034").splice(1,3); 
    // converts these hex strings to decimal and combines them into a "rgb(#, #, #)" formatted color string
    var rgb = 'rgb(' + colors.map(function (color){return parseInt(color, 16)}).join(', ') + ')';
    // go through each element in the page
    $("*").each(function (index, element) {
        // go through each color-related style "key"
        filteredKeys.forEach(function(key) {
            // if the element's value for this key matches the color to be replaced...
            if ($(element).css(key) == rgb) {
                // ...replace that color with the replacement color
                $(element).css(key, "#456780");
            }
        });
    });
    div {
        height: 50px;
        width: 50px;
    }
    .common-color {
        color:#789034;
    }
    .new-cls {
        border-style: solid;
        border-color:#789034;
    }
    .awesome-one {
        background-color:#789034;
        height:200px;
        width:300px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="common-color">hello</div>
    <p class="new-cls">cool</p>
    <div class="awesome-one"></div>

    编辑:

    或者,如果您愿意,这里有一个简单的函数可以使用。颜色 1 将替换为颜色 2:

    function replaceColor(color1, color2) {
        var keys = Object.values(window.getComputedStyle($('html').get(0)));
        var filteredKeys = keys.filter(function (key){return key.indexOf('color') > -1});
        var colors = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color1).splice(1,3); 
        var rgb = 'rgb(' + colors.map(function (color){return parseInt(color, 16)}).join(', ') + ')';
        $("*").each(function (index, element) {
            filteredKeys.forEach(function(key) {
                if ($(element).css(key) == rgb) {
                    $(element).css(key, color2);
                }
            });
        });
    }
    

    【讨论】:

      【解决方案5】:

      你可以考虑用 jquery 来改变它。

      $(function() {
        $('.awesome-one').hover( function(){
           $(this).css('background-color', '#789034');
        },
        function(){
           $(this).css('background-color', '#456780');
        });
      });
      

      【讨论】:

      • 您的代码仅用于背景,我清楚地提到它应该在所有发现 #789034 的地方更改为 #456780- 谢谢
      猜你喜欢
      • 2015-05-15
      • 1970-01-01
      • 2020-03-17
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2013-02-14
      相关资源
      最近更新 更多