我有一个要求,我必须在其中显示两行文本并添加...如果它溢出 我的div宽度是固定的。(甚至高度也可以认为是固定的)。
实际文本如下所示:
1
Lorem Ipsum 很简单
打印的虚拟文本
和排版行业。
2
Lorem Ipsum 只是文本
打印和类型
行业。
预期:
1
Lorem Ipsum 就是
打印的虚拟文本...
2
Lorem Ipsum 只是文本
打印和打字...
我不想让插件重载(三个点的 jquery 插件可以做到这一点)。
我打算在 div 宽度固定时切割(拆分)字符串。
提前致谢。
最佳答案
更新:看起来 text-overflow
只对水平 chop 有用。
这是一个应该可以工作的小 jQuery。
尝试一下: http://jsfiddle.net/UfxYQ/
var $container = $('#container');
var $text = $('#text');
var originalText = $text.text();
var temp = originalText;
if( $container.outerHeight() < $text.outerHeight() ) {
while($container.outerHeight() < $text.outerHeight()) {
$text.text( temp = temp.substr(0, temp.length-1) );
}
$text.text( temp = temp.substr(0, temp.length-3) );
$text.append('...');
}
HTML
<div id='container'>
<span id='text'>Lorem Ipsum is simply
dummy text of the printing
and typesetting industry.
</span>
</div>
CSS
#container {
width: 150px;
height: 50px;
line-height: 25px;
position: relative;
}
您不会拥有完整的跨浏览器支持,但是接近了。 IE6+、Safari、Konqueror 和 Opera(具有 Opera 特定属性)支持名为 text-overflow
的 CSS 属性。
#myOverflowDiv {
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
}
关于javascript - 如何在 javascript 中剪切字符串,使其恰好适合两行并在末尾添加 ...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358700/