使用jquery替换css中的特定颜色代码

时间:2015-06-09 04:43:02

标签: jquery css html5 twitter-bootstrap

我想将#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;
}

5 个答案:

答案 0 :(得分:10)

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

首先,致电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到hex进行快速转换以进行比较。这使用内部rgb2hex()函数。

我希望这就是你要找的东西。

function colorReplace(findHexColor, replaceWith) {
  // Convert rgb color strings to hex
  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>

答案 1 :(得分:2)

为什么,它的小学,亲爱的沃森。只需抓住所有可能的样式键,检查它们是否包含单词颜色,然后使用复杂的正则表达式系统将所有出现的颜色替换为新颜色。

&#13;
&#13;
// 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");
        }
    });
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

修改

或者,如果你愿意,这里有一个简单的功能。颜色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);
            }
        });
    });
}

Drakes's solution是我的解决方案的修改版本。他改变了一些方法,例如将颜色值从rgb(#,#,#)解析为十六进制而不是相反,以进行颜色比较(使用从yet another solution借来的函数)并重新解释说明,以及做了几个其他的微不足道的修改。我的代码使用eachforEach代替mapreduce来遍历数组,这不是解决问题的最佳方法。

答案 2 :(得分:1)

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

:root {   
    --color1: #789034; 
}

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

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

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

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

答案 3 :(得分:0)

您可能需要尝试以下操作:

将样式表内嵌到文档中,由样式标记包装:

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

现在您可以通过

获取此内容
var myCss = $("#myStyles").text();

然后继续做替换魔术:

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

最后,有希望的努力,把它放回DOM:

$("#myStyles").text(myCss);

但即使这应该有效,我觉得你很可能带来XY problem

答案 4 :(得分:-1)

您可以考虑使用jquery更改它。

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