2017-05-18 282 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,如果是这样的话?“(续) –