你得到一個字的長度,但應用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