簡體   English   中英

更改字符串中每個單詞的字體顏色(JS或PHP)

[英]Change font color for each word in a string (JS or PHP)

我已經搜索過,但找不到解決方案來增加標題中3個或4個單詞的字體顏色(例如,亮度+ 10%)。 字體顏色將首先在SCSS中使用顏色變量設置。

標題示例:

這是我的新標題

在此示例中,假設標題為“深藍色”。這些單詞為:

Here = darker blue
Is = navy blue
My = medium blue
New Title = light blue

這里有一個類似的文章: JavaScript文本顏色更改為數組中的每個單詞,但這是在數組中搜索關鍵字,而不是字符串中的每個單詞。

我也遇到過像這樣的基本CSS / HTML唯一解決方案,該解決方案不起作用: HTML:更改文本字符串中特定單詞的顏色

注意:我將在php變量中返回標題(字符串)-萬一PHP中有解決方案。

目標:我需要為字符串中的每個單詞增加字體顏色(甚至將連續的單詞用跨距包裝並增加SCSS var)。

更新我已經添加了一個jsfiddle鏈接( http://jsfiddle.net/revive/xyy04u7d/ ),以展示JS實現,這要歸功於Tushar,並對正則表達式中的&符號進行了一些更改。

這是PHP實現

<?php
    $title = "SIMPLE TITLE & WITHOUT COLORS";
    $words   = preg_split('/\s+(?!&)/', $title);
?> 
<h3 class="colors blue">
<?php foreach($words as $word):?>
    <span><?php echo $word; ?></span>
<?php endforeach; ?>
</h3>

這是一個演示,該演示基於空格分割單詞,並使用類名將每個單詞包裝在一個范圍內。 您可以根據需要使用樣式名稱來設置元素的樣式。

 var str = "Here Is My New Title which may well be way too longer than I have actually provided"; var res = ""; str.split(/\\s+/).forEach(function(str, idx) { //Would only work with the string in question //res += "<span class='color-"+(idx+1)+"'>" + str + " </span>"; //Would work with any amount of words in a string, applying the same set of classes every 5 words. res += "<span class='color-" + (idx % 5) + "'>" + str + " </span>"; }); $("body").append(res); 
 .color-0 { color: violet; } .color-1 { color: indigo; } .color-2 { color: blue; } .color-3 { color: green; } .color-4 { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

您可以將每個單詞包裝在單獨的span或任何其他元素中,然后可以使用CSS nth-child屬性設置不同的樣式。

使用這種方法,您不必創建單獨的類,並且它適用於字符串中任意數量的單詞。

 var str = 'Split the Text by one or more spaces. Join them to make them wrap in span elements. Then use CSS nthChild Properties :)'; str = '<span>' + str.split(/\\s+/).join('</span> <span>') + '</span>'; $(document.body).append(str); 
 span:nth-child(4n) { color: red; } span:nth-child(4n + 1) { color: green; } span:nth-child(4n + 2) { color: blue; } span:nth-child(4n + 3) { color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 


您還可以按以下方式使用正則表達式:

 $("h1").html(function(i, oldHtml) { return oldHtml.replace(/(\\S+)/g, '<span>$1</span>'); }); 
 span:nth-child(4n) { color: red; } span:nth-child(4n + 1) { color: green; } span:nth-child(4n + 2) { color: blue; } span:nth-child(4n + 3) { color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <h1> Hello World! Have a Great Day! </h1> 

這是類似的答案

更改文字

first = str.substring(0,till);
    second = str.substring(till,last);
    //Print data
    $(this).html("<span style=color:"+setting.color+">"+first+"</span>"+ second);

下載插件: string_color

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM