首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据段落中的文本值更改文本颜色

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

Stack Overflow用户
提问于 2016-09-10 20:54:35
回答 1查看 3.1K关注 0票数 1

我有一个段落或h1与“该项目的颜色是品红”或“此输出是红色”。带有颜色(红色、黑色、青色、品红或黄色)的文本可能位于段落或h1标记的某个位置。

到目前为止我的密码。

代码语言:javascript
复制
<div id="foo">
  red magenta yellow black blue
</div>
<h1>magenta toner cartridge</h1>

CSS

代码语言:javascript
复制
.red{
  color: red;   
}
.magenta{
  color: magenta;   
}

JAVASCRIPT

代码语言: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>"));
});

问题如何根据元素中的文本动态地更改单词洋红和红色的背景和文本颜色?

EN

回答 1

Stack Overflow用户

发布于 2016-09-10 21:54:35

像这样的东西会有用的:

代码语言:javascript
复制
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');
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39430488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档