使用jquery将css样式添加到特定文本

时间:2015-03-03 18:43:41

标签: jquery css

如何为div中的特定文本或字符添加样式?

<div class="test">blocks of texts here.</div>

我想为单词&#34; text&#34;添加颜色。不使用任何标记,如span来封闭它。提前谢谢。

5 个答案:

答案 0 :(得分:3)

如果不将文本包装到元素中,则无法执行此操作。但你可以使用jQuery进行包装:

var $test = $('.test').html();
$test = $test.replace(/texts/gi, '<span class="tomato">texts</span>');
$('.test').html($test);

http://jsfiddle.net/r36xjzs7/

这将重新创建整个元素,因此效率不高。

答案 1 :(得分:1)

您可以使用以下功能设置文字中任意字词的样式:

function style_word(text_id, word, css_style) {
    html = $('#' + text_id).html();
    replace = word;
    re = new RegExp(replace,"gi");
    $('#' + text_id).html(html.replace(re, "<span style='" + css_style + "'>" + word + "</span>"));
    }

只需定位包含文字的元素,选择单词进行样式处理,然后选择css 样式

以下是示例

<div id='my_words'>
There is little doubt that stack overflow has become the de facto method of building software. There is no other way to ensure we are not reinventing the wheel, and benefiting from the power of massive collaboration and variation. A network of contributing individuals will always produce the most optimal solution, and this cannot be matched by the singular efforts of an individual.
</div>

用法

style_word('my_words', 'software', 'color: hotpink')

<强>结果:

enter image description here

style_word('my_words', 'software', 'font-style: italic')

enter image description here

它还支持在一个调用中传递多个样式

style_word('my_words', 'software', 'font-size: 24px; color: blue; font-weight: bold; font-style: italic')

enter image description here

答案 2 :(得分:0)

我个人会将这些单词包装在span元素中。

<div class="test">blocks of <span id="blueText">texts</span> here.</div>

然后你可以打电话

$("#blueText").css('color', 'blue');

答案 3 :(得分:0)

嗯,你做不到。

这是一个很好的问题: aaronk6 问你为什么不在一个范围内包装这个词,原因是CSS是一种分离内容和外观的工具,因此正是应该用于什么。此外,您可能会发现自己可以编辑CSS但无法访问html。

There's a great article by Chris Coyier关于这个问题,需要一些额外的CSS选择器,它们会派上用场。

话虽如此, Cyber​​netic 的解决方案很棒(荣誉)!如果你要在文件中进行这样的改动,并且不能(或不会)触摸html,那么javascript就是你要走的路。但是我没有硬编码CSS规则,而是建议你给它一个类的跨度,并在外部CSS文件中制定规则。代码将:

json_file_names = sorted(glob.glob("./Intel_Shared_Data/gtFine/train/*/*.json")) 
for fn in json_file_names:
    #print fn
    #temp = temp + 1
    #count = 0
    d = json.load(open(fn))
    objects = d["objects"]
    for j in range(len(objects)):

所以,如果您只想更改function style_word(text_element, word_to_style) { html = text_element.html(); classID = "style-"+word_to_style; re = new RegExp(word_to_style,"gi"); new_html = html.replace(re, "<span class='"+classID+"'>"+word_to_style+"</span>"); text_element.html(new_html); } 中的“条形码”,请致电:

<p>foo bar</p>

然后添加CSS规则:

style_word( $("p"), "bar" ); //jQuery element, then word inside

PS:对不起,这不是对Cyber​​netic帖子的评论......我还不能发表评论。

答案 4 :(得分:-1)

$(".test").css("color","white");