如何在javascript中剪切字符串,使其恰好适合两行并在最后添加....

jaa*_*aan 7 javascript jquery

我有一个要求,我必须显示两行的文本并添加...如果它溢出我的div宽度是固定的.(甚至高度可以被视为固定).

实际文本如下所示:

1

Lorem Ipsum只是
印刷
和排版行业的虚拟文本.

2

Lorem Ipsum只是
印刷和类型
行业的文本.

预期:

1

Lorem Ipsum只是
打印的虚拟文本......

2

Lorem Ipsum只是简单
的印刷文字和典型...

我不想用插件重载(三点jquery插件就是这样).

我打算只修剪(拆分)字符串,因为div宽度是固定的.

提前致谢.

use*_*716 6

更新:看起来text-overflow只对水平截断有用.

这是一个应该工作的小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('...');
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div id='container'>
    <span id='text'>Lorem Ipsum is simply
        dummy text of the printing
        and typesetting industry.
    </span>
</div>?
Run Code Online (Sandbox Code Playgroud)

CSS

#container {
    width: 150px;
    height: 50px;
    line-height: 25px;
    position: relative;
}
Run Code Online (Sandbox Code Playgroud)

您将无法获得完整的跨浏览器支持,但请关闭.text-overflowIE6 +,Safari,Konqueror和Opera(具有Opera特定属性)支持一种称为CSS属性.

#myOverflowDiv {
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)

http://www.quirksmode.org/css/textoverflow.html

http://www.quirksmode.org/css/contents.html#t413