将CSS应用于单个单词

时间:2013-05-04 23:54:20

标签: html css styles

是否可以以这样一种方式应用CSS,即只要元素中有某个单词并以某种方式标记该单词,它就会检测到它?我知道我可以添加<span style="...">word</span><span class="...">word</span>内嵌HTML,但这不会自动检测到该字词。有没有办法在CSS中完全做到这一点?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:4)

没有办法只用css做到这一点。您可以使用包装版本替换该单词的所有实例,并根据您的示例http://jsfiddle.net/w9VbP/应用样式:

JS

var word = 'hello';
var replacement = '<span class="theword">' + word + '</span>';

var re = new RegExp(word, 'ig');

document.body.innerHTML = document.body.innerHTML.replace(re, replacement);

CSS

.theword
{
    color:red;
}

答案 1 :(得分:0)

您可以使用jQuery轻松完成。我正在var text中存储正文的html标记并用sample替换<span class="change">sample1</span>并放回正文的更新的html标记。显然,你必须将这个jQuery放在head部分中除了hQuery之外,jQuery函数中的sample字符串也将替换为<span class="change">sample1</span>

jQuery函数

$('body').each(function() {
    var text = $(this).html().replace(/sample/g,'<span class="change">sample1</span>');
    $(this).html(text);
});

Css:

.change{
color:red;
background:blue;
}

Working jsFiddle