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

标签 jquery css html twitter-bootstrap

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

我有一个像下面这样的 main.css 文件:

.common-color
{
  color:#789034;
}

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

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

我想使用 jquery 将 #789034 代码替换为 #456780 之类的另一个代码:

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

最佳答案

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

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

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

所有包含“color”的样式属性(如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
  // 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>

关于jquery - 使用jquery替换css中的特定颜色代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30723177/

相关文章:

css - 位置 : absolute without setting top/left/bottom/right?

html - 如何让所有图像都显示在我的 slider 上,同时用自己的 div 标签区分每个图像?

javascript - $ ('document' ).ready() 函数在ajax响应后不起作用

javascript - 使用源数据属性自动完成?

html - CSS - 样式表

html - 需要将样式表中的div元素居中对齐

javascript - 使用javascript覆盖css文件的 'on the fly' css规则选择器

javascript - 如何为不透明的 div 设置时间?

javascript - 如何使用 jQuery 处理类(由 jQuery 制作)?

javascript - 使用jquery提交时如何将数组添加到表单?