如何根据段落内的文本值更改文本颜色


How to change the text color based on the text value inside a paragraph

我有一个段落或h1,"这个项目的颜色是Magenta"或"这个输出是红色"。带颜色的文本(红色、黑色、青色、品红或黄色)可以在段落或h1标签的某个地方。

我的代码到目前为止。

<div id="foo">
  red magenta yellow black blue
</div>
<h1>magenta toner cartridge</h1>
CSS

.red{
  color: red;   
}
.magenta{
  color: magenta;   
}
JAVASCRIPT

$("div:contains('magenta')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("magenta", "<span class='magenta'>magenta</span>"));
});
$("div:contains('red')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("red", "<span class='red'>red</span>"));
});

$("h1:contains('magenta')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("magenta", "<span class='magenta'>MAGENTA</span>"));
});

如何根据元素内的文本动态更改单词Magenta和Red的背景和文本颜色?

可以这样做:

 

var colors={'red':{'background-color':'#ff0000',"color":'#ffffff'},
            'black':{'background-color':'#000000',"color":'#ffffff'},
            'cyan':{'background-color':'#00ffff',"color":'#ffffff'},
            'magenta':{'background-color':'#ff00ff',"color":'#ffffff'},
            'yellow':{'background-color':'#ffff00',"color":'#000000'}
            };
            
function colorize(colorsArr, selector) {
  $.each(colorsArr, function(color, obj) {
    var regex = new RegExp('(' + color + ')', 'gi');
    var style = ' style="' + JSON.stringify(obj).replace(/[{"}]/g, '').replace(',', ';') + '" '
    var $element = $(selector);
    var curComtent = $element.html();
    if (curComtent.match(regex)) {
      var newContent = curComtent.replace(regex, '<span ' + style + '>$1</span>');
    }
    $element.html(newContent); 
  });
}
colorize(colors, '.test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="test">
  I have a paragraph or h1 with "the color of this item is Magenta" or "this output is Red". So how can I change the background and text color of the word Magenta and Red dynamically. The text with color (red, black, cyan, magenta or yellow) could be somewhere
  on the paragraph or h1 tag.
</p>