2017-05-18 271 views
0

我們有什麼可以將樣式應用於一組匹配關鍵字的CSS嗎?css中字符串的模式匹配

例如,我有一個單詞列表{「歷史」,「領導者」,「情感」,「時間」 ...}

我想CSS樣式應用到所有關鍵字與以下段落中的上述列表相匹配。


「縱觀人類歷史,或最大領導和思想家都用文字的力量來改變我們的情緒,爭取我們自己的原因,塑造的過程命運。言語不僅可以創造情緒,他們創造行動。並從我們的行動流向我們生活的結果。「託尼羅賓斯

+2

* 「難道我們有什麼的CSS樣式哪裏可以應用到匹配的關鍵字組合?」 * - 不。 – Santi

+2

不,你需要'歷史'可以用JavaScript動態插入。 –

+1

您需要使用js將它們包裹在一個類中並附上類 - css本身不能這樣做 – Pete

回答

0

感謝所有的投入。在應用css之前,我會去javascript編輯html代碼 。

這是一種方法,展示如何通過數組循環:

['history', 'leaders', 'emotions', 'time'] 

和大膽的每個文本的話。

var wordsToHighlight = ['history', 'leaders', 'emotions', 'time']; 
 

 
var paragraph2 = document.getElementsByTagName('p')[1]; 
 
var paragraph2Text = paragraph2.innerHTML; 
 
var paragraph2RichText = paragraph2Text; 
 

 
for (var i = 0; i < wordsToHighlight.length; i++) { 
 
    var regex = new RegExp('('+ wordsToHighlight[i] + ')', 'gi'); 
 
    paragraph2RichText = paragraph2RichText.replace(regex, '<strong>$1</strong>'); 
 
} 
 

 
paragraph2.innerHTML = paragraph2RichText;
<p>「Throughout human history, or greatest leaders and thinkers have used the power of words to transform our emotions, to enlist us in their causes, and to shape the course of destiny. Words can not only create emotions, they create actions. And from our actions flow the results of our lives.」 Tony Robbins</p> 
 
<p>「Throughout human history, or greatest leaders and thinkers have used the power of words to transform our emotions, to enlist us in their causes, and to shape the course of destiny. Words can not only create emotions, they create actions. And from our actions flow the results of our lives.」 Tony Robbins</p>

+1

他說「在CSS中」。 – Rob

+0

您上面的評論遇到了一點小小的敵意,@Rob。 OP包含一個「javascript」標籤。你刪除了哪個。他還寫道:感謝所有的投入。我會在應用css._之前使用javascript編輯html代碼。我的回答是對該評論的回覆。我相信我們都不比OP更清楚OP的問題。 – Rounin

+1

單純出現[javascript]標籤恕我直言並不意味着OP願意或渴望接受JS解決方案。相反,他在這篇文章的標題和正文中都重複了「CSS」。他提出的問題是「我們有CSS嗎?」和「我想申請CSS風格」。我們都看到很多情況下,OP在他們的帖子上標記。從這個意義上說,我同意編輯刪除「javascript」標籤。如果用戶想要使用JS,那麼假設他會添加一個句子並不是不合理的,*或者,我是否必須使用JS,如果是這樣的話?「(續) –