我如何只显示使用CSS的一部分字符串 [英] How do I only display part of a string using css
问题描述
我希望能够显示最多10个字符的字符串。如果字符串超过10个字符,我想在末尾附加'...'。
I want to be able to display a string of characters up to 10 characters. If the string goes over 10 characters, I'd like to append '...' to the end.
例如,如果我有字符串:
For example, if I have the string:
'helloworldmynameisryan'
我希望它能像这样显示:
I want it to be displayed like so:
'helloworld...'
'I'我只是在像这样的div中显示我的字符串:
I'm just displaying my string in a div like this:
<div>DisplayMessage</div>
是否有一个我可以创建的类只适用于字符串超过10个字符的情况? / p>
Is there a class that I could create that would only apply if the string were over 10 char?
推荐答案
不幸的是,没有一个好的跨浏览器的方式来使用CSS。 'text-overflow'依赖于字符串的宽度,而不是字符串的长度。
Unfortunately there isn't a good cross browser way to do this using only CSS. 'text-overflow' relies on the width of the string, and not the length of string as you need.
你可以在javascript中使用.length属性的字符串(str.length> 10){
;
You can use the .length property of strings in javascript to achieve this
function ellipsify (str) {
if (str.length > 10) {
return (str.substring(0, 10) + "...");
}
else {
return str;
}
}
希望这有助于您。
这篇关于我如何只显示使用CSS的一部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!