使用CSS或jQuery更改每行的颜色第一个单词 [英] Change color first word of each line with CSS or jQuery

查看:105
本文介绍了使用CSS或jQuery更改每行的颜色第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定位每行的第一个单词将颜色更改为只有第一个单词。现在由后端的 textarea 填充。

Im trying to target the first word of each line to change the color to only the first word on it. Right now this is being populated by a textarea on the backend.

<div class="items">
67 small businesses has worked with us since the beginning of time
<br>
<br>3:1 ratio of apple products to humans
<br>
<br>2400 hours clocked in 2012
<br>
<br>13.7 number of times "So what exactly do you do?" is asked weekly
<br>
<br>1628 number of Starbucks K Cups consumed
<br>
<br>32 collective years of creative experience<br></div>

我想要实现的是将< span> / code>在每个第一个单词前面使用 jQuery 或类似的:

what I am trying to accomplish is to put a <span> in front of each first word using jQuery or something like so:

<div class="items">
    <span class="color">67</span> small businesses has worked with us since the beginning of time
    <br>
    <br><span class="color">3:1</span> ratio of apple products to humans
</div>

任何帮助都将非常感谢!

any help would be greatly appreciated!

推荐答案

拆分拆分(或换行符?),并在第一个单词周围添加一个单词mathcing regex:

split on breaks (or newlines ?), and add a span around the first word with a word mathcing regex :

$('.items').html(function(_,html) {
    var lines = html.split(/<br\s*[\/]?>/gi);
    for (var i=lines.length; i--;) {
        lines[i] = $.trim(lines[i]).replace(/^(\w+)/, '<span class="red">$1</span>')
    }
    return lines.join('<br>');
});

FIDDLE

这篇关于使用CSS或jQuery更改每行的颜色第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆