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

问题描述 投票:1回答:5

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

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

我想为“文本”这个词添加颜色,而不使用任何标记,例如span来封闭它。提前致谢。

jquery css
5个回答
3
投票

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

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

http://jsfiddle.net/r36xjzs7/

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


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


0
投票

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

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

然后你可以打电话

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

0
投票

好吧,你做不到。

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

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

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

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>只更改“bar”,你会打电话:

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

然后添加一个CSS规则:

.style-bar{
    color: #123;
}

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


-1
投票
$(".test").css("color","white");
© www.soinside.com 2019 - 2024. All rights reserved.