JavaScript — Как изменить цвет текста на основе значения текста внутри абзаца

У меня есть параграф или h1 с «цвет этого элемента — пурпурный» или «этот вывод — красный». Цветной текст (красный, черный, голубой, пурпурный или желтый) может находиться где-то в абзаце или теге h1.

Мой код пока что.

HTML

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

Вопрос
Как я могу динамически изменить фон и цвет текста слова «пурпурный» и «красный» на основе текста внутри элемента?

0

Решение

Примерно так будет работать:

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>
1

Другие решения

Лучше всего использовать регулярные выражения для определения названия цвета. Это может потребовать, чтобы вы уже определили массив возможных цветов. Процесс медленный, кстати.

-2

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector