如何将长文本放入固定宽度的列中,我只有一行文本空间?需要将文本剪切为固定宽度(比方说100px),我想在最后添加点“...”。像这样的东西:
给定字符串:
Some really long string that I need to fit in there!
固定宽度列中的所需输出应为:
Some really long string...
答案 0 :(得分:73)
你可以单独用CSS做到这一点:
.box {
-o-text-overflow: ellipsis; /* Opera */
text-overflow: ellipsis; /* IE, Safari (WebKit) */
overflow:hidden; /* don't show excess chars */
white-space:nowrap; /* force single line */
width: 300px; /* fixed width */
}
注意:您需要查看最新的浏览器支持。
答案 1 :(得分:2)
就像一些像Gordon的回答一样的CSS。刚刚为display:block
或<a>
等内联元素添加了<p>
属性:
a#myText{
display: block;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
width: 300px;
}
您可以在许多浏览器中使用它,就像您在此链接上看到的那样: http://caniuse.com/#search=text-overflow
答案 2 :(得分:0)
我有一个类似的问题,我解决它的方法是将字符串删除到60个字符并在其末尾附加一个“...”。
丑陋的解决方案?是的,但除非有jQuery解决方案,否则它可能是你最好的选择。
如果您正在使用Smarty,这就是我解决问题的方法:
{$my_string|truncate:60}
答案 3 :(得分:0)
这是我用来截断字符串的函数。像这里的大多数建议一样,它使用substr截断字符串,但它会避免分割字符串中间字:
function truncate_text($string, $min_chars, $append = ' …') {
$chars = strpos($string, " ", $min_chars);
$truncated_string = substr($string, 0, $chars) . $append;
return $truncated_rstring;
}
答案 4 :(得分:0)
我认为在N个字符之后的简单剪切文字不是你想要的。这不是一个解决方案,因为下面的文字有15个字符长度:iiiiiiiiiiiiiii,mmmmmmmmmmmmmmm - 注意第二个“单词”大约是第一个单词的三倍。
JavaScript可能是一个解决方案:
首先准备你的加价:
<p id="abc">{TEXT}</p>
{TEXT}
的文字被截断为150个字符+ ...
现在,当我们有一个很好的JavaScript基础时,我们可以尝试制作您想要的东西:
<html>
<head>
<style type="text/css">
#abc {
width: 100px;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var ref = document.getElementById("abc");
var text = ref.text;
ref.removeChild(ref.firstChild);
ref.appendChild(document.createTextNode("..."));
var maxHeight = ref.offsetHeight;
var pos = 0;
while (ref.offsetHeight <= maxHeight) {
var insert = text.substring(0, ++pos) + "...";
var finalReplace = ref.replaceChild(document.createTextNode(insert), ref.firstChild);
}
ref.replaceChild(finalReplace, ref.firstChild);
}, false);
</script>
</head>
<body>
<p id="abc">My very, very, very, very, very, very, very long text...</p>
</body>
</html>