2016-09-10 11 views
0

"このアイテムの色はマゼンタです"または "この出力は赤です"という段落または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

あなたは、いくつかのコードを投稿する必要があります。 –

+0

何か試してみたら、それも投稿してください。 – yezzz

+0

http://jsfiddle.net/5bSgc/72/ –

答えて

-2

正規表現を使用して色の名前を検出することをお勧めします。可能な色の配列を既に定義しておく必要があるかもしれません。プロセスは遅いbtwです。

+0

これはコメントではありません。 – DelightedD0D

+0

コードを書く代わりにヒントを与える方がいいです。私がコードを与えると、彼はそれをコピーすることができ、何も学ばないでしょう。私はこれが最高の答えだと信じています。 –

1

このような何かが働くだろう:


 

 

 

 

 
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>

+0

Downvoterが説明する必要があります。これは要件を満たしています。 – DelightedD0D

関連する問題