我有一个段落或h1与“该项目的颜色是品红”或“此输出是红色”。带有颜色(红色、黑色、青色、品红或黄色)的文本可能位于段落或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>"));
});问题如何根据元素中的文本动态地更改单词洋红和红色的背景和文本颜色?
发布于 2016-09-10 21:54:35
像这样的东西会有用的:
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>
https://stackoverflow.com/questions/39430488
复制相似问题