你得到一个字的长度,但应用CSS规则的全部文本。你需要用文字分隔文本,并将其应用于其中的一些。
var container = $("#myText");
var words = container.text().split(' ');
container.empty();
for (var i = 0; i < words.length; i++)
{
if (words[i].length > 20)
{
$("<span/>").text(words[i] + " ").addClass('longword').appendTo(container);
} else {
container.html(container.html() + words[i] + " ");
}
}
.longword {
font-weight: bold;
background-color: #FF0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myText">
Here is the simple text which contains some very long words like pseudopseudohypoparathyroidism or antidisestablishmentarianism.
</div>
产生的HTML看起来像这样:
Here is the simple text which contains some very long words
like <span class="longword">pseudopseudohypoparathyroidism</span> or
<span class="longword">antidisestablishmentarianism</span>.
你的问题并不清楚。你的意思是说你只想将这种CSS样式应用于超过20个字符的单个单词? –
@RoryMcCrossan是 – Pepe