javascript:搜索并用不同的颜色代码替换十六进制颜色代码

javascript: search and replace hexadecimal color code with a different color code

本文关键字:代码 颜色 替换 十六进制 搜索 javascript      更新时间:2023-09-26

我正试图使用Javascript在Wordpress页面上搜索特定的十六进制代码,并用另一个代码替换该代码。代码是#FF4500,我想用#FFFFFF代替它。我已经使用JSFiddle在网上尝试了几种解决方案,但一直无法使其发挥作用。

HTML:

<div style="padding:5px;background:#FF4500;text-align:center;">Some Text Here</div><br>

以下是我尝试过的:

$(document).ready(function() {
    $('div').each(function () {
        var $this = $(this);
        $this.html($this.text().replace(*FF4500, FFFFFF));
    });
});

香草。

function changeColorRecursive(root, oldColor, newColor) {
  if (root.style) {
    for (var i in root.style) {
      if (typeof(root.style[i]) == 'string' && root.style[i].toLowerCase() == oldColor.toLowerCase())
        root.style[i] = newColor;
    }
  }
  if (root.childNodes) {
    for (var i = 0; i < root.childNodes.length; i++) {
      changeColorRecursive(root.childNodes[i], oldColor, newColor);
    }
  }
}
changeColorRecursive(document.body, "#FF4500", "#FFFFFF");

好吧,我太慢了,但我添加了一些特效。

下次你应该自己开始一个新的JSFiddle。

rgb匹配肯定很脆弱,应该规范化为#RRGGBB,但这是第一个工作版本。

尝试upatedhttp://jsfiddle.net/anaran/he6WE/

JS

$(document).ready(function() {
    $('div').each(function () {
        console.log(this.style.backgroundColor);
        if (this.style.backgroundColor.match(/^rgb'(255, 69, 0')$/)) {
            this.style.transition = 'linear 2s';
            this.style.backgroundColor = '#FFFFFF';
    }
    });
});

当我在那里的时候…

http://jsfiddle.net/anaran/he6WE/35/使用jQuery UI 1.10.3jQuery 2.0.2,显然支持jQuery Color:

$(document).ready(function() {
    $('div').each(function () {
        // console.warn($.Color(this.style.backgroundColor).toHexString(false));
        if ($.Color(this.style.backgroundColor).toHexString(false).match(/^#FF4500$/i)) {
            this.style.transition = 'linear 2s';
            this.style.backgroundColor = '#FFFFFF';
    }
    });
});

您无法真正与十六进制进行比较,因为css()返回rgb。你不能要求背景,因为你也有其他属性。好的,使用jQuery,我认为这应该有效:

$(document).ready(function(){ 
  $('div').each(function () {
    if( $(this).css('background-color') == 'rgb(255, 69, 0)') {
      $(this).css('background-color', '#FFFFFF')
    }
  }); 
});

您可以使用JQuery属性选择器来执行此操作:

$("div[style*='background:#FF4500;']").each(function() {
    var currStyle = $(this).attr("style");
    $(this).attr("style", currStyle.replace("background:#FF4500;", "background:#FFFFFF;"));
});

选择器将获取包含background:#FF4500;样式的所有<div>元素,然后进入每个元素并用新样式替换该背景样式。

这在很大程度上依赖于持续创建的background样式(考虑到它来自Wordpress,我认为会是这样)。此外,我在替换中包含了单词"background",以避免在样式的其他地方替换该十六进制值。