简体   繁体   English

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

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

I have a paragraph or h1 with "the color of this item is Magenta" or "this output is Red".我有一个段落或 h1 带有“此项目的颜色为洋红色”或“此输出为红色”。 The text with color (red, black, cyan, magenta or yellow) could be somewhere on the paragraph or h1 tag.带有颜色(红色、黑色、青色、洋红色或黄色)的文本可能位于段落或 h1 标签的某个位置。

My code so far.我的代码到目前为止。

HTML HTML

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

CSS 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>"));
});

Question How can I change the background and text color of the word Magenta and Red dynamically based on the text within the element?问题如何根据元素内的文本动态更改 Magenta 和 Red 一词的背景和文本颜色?

Something like this would work: 这样的事情会起作用:

 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> 

It's best to use regular expressions to detect color name. 最好使用正则表达式来检测颜色名称。 That might require for you to have already defined array of possible colors. 这可能需要您已经定义了可能的颜色数组。 Process is slow btw. 顺便说一句,过程缓慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM