2015-09-28 49 views
2

我只找到一种方法来计算内容的字符,但我需要的是字长。例如,在20个字符的CSS 话做的事,但不如果20个字符是一个以上的字 ...通过字长运行脚本,而不是通过字符计数

That's我怎么努力,但它计算字符;(

var s = $(".text").html(); 

if (s.split(' ').length > 20) { 
    $(".text").css({ 
     'background-color' : '#F00', 
     'font-weight' : 'bold' 
    }); 
} 

这是可能使用jQuery

+0

你的问题并不清楚。你的意思是说你只想将这种CSS样式应用于超过20个字符的单个单词? –

+0

@RoryMcCrossan是 – Pepe

回答

1

你得到一个字的长度,但应用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>. 
+0

大thx支持,这绝对是我所期待的! – Pepe

0

您现在基本上计算的话为了检查是否有句话超过20个字符,你必须做这样的事情:?

s.split(' ').some(function(a) {return a.length > 20}) 

The definition of some can be found here.

0
s.split(" ") will return you an array of strings. 

只是改变线

如果(str.split(”“)。长度> 20)

如果(str.split(”“)[0]。长度> 20)

+0

thx支持 - 我尝试这种方式,但在我看来,它不工作。 – Pepe