簡體   English   中英

如何在javascript中剪切字符串,使其恰好適合兩行並在最后添加....

[英]How to cut the string in javascript so that it fits exactly two lines & add … at the end

我有一個要求,我必須顯示兩行的文本並添加...如果它溢出我的div寬度是固定的。(甚至高度可以被視為固定)。

實際文本如下所示:

1

Lorem Ipsum很簡單
印刷的虛擬文本
和排版行業。

2

Lorem Ipsum只是文字
印刷和類型
行業。

預期:

1

Lorem Ipsum很簡單
印刷品的虛擬文字......

2

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

我不想用插件重載(三點jquery插件就是這樣)。

我打算只修剪(拆分)字符串,因為div寬度是固定的。

提前致謝。

更新:看起來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('...');
}

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; } 

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

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

CSS文本溢出屬性是最好的方式,但尚未得到所有瀏覽器的支持。 如果您想使用Javascript,可以創建一個屏幕外元素。 使用CSS(由腳本生成)為其提供與目標相同的寬度和字體,高度為“2em”(即2行)。 運行一個循環,一次一個字母地將文本添加到其中,直到您用完字母或高度變化。 當高度增加時,你知道你超過了兩條線。

當然,您還需要考慮“...”的寬度,因此您可以將其附加到您要添加的字母中。

確保元素在屏幕外而不是使用“display:none”,因為非顯示元素沒有高度。 “可見性:隱藏”可能起作用; 我沒試過。

只是用戶113716的帖子的補充。 更清潔的做法:

var $container = $('#container');
var $text = $('#text');
var temp = $text.text();

if ($container.height() < $text.outerHeight()) {
  while($container.height() < $text.outerHeight()) {
    temp = temp.substr(0, temp.length-1)
    $text.text(temp + '...');
  }
}

http://jsfiddle.net/YR7F2/

一個簡潔的方法是使用一個小jQuery插件...

$.fn.trimToParentHeight = function(options) {
    options = $.extend($.fn.trimToParentHeight.defaults, options);

    return this.each(function(index, text) {
        text = $(text);
        var height = parseInt(text.parent().height());
        var temp = text.text();
        while(parseInt(text.outerHeight()) > height && temp.length>0) {
            temp = temp.substr(0, temp.length-1)
            text.text(temp +  options.ellipsis);
        }
    });
}

$.fn.trimToParentHeight.defaults = {
    ellipsis: '...'
};

那你就可以......

$(".container .text").trimToParentHeight()

...只要容器是文本的直接父級。

string="test/firstpage/secondpage/thirdpage";

string.split("/").slice(0, 1);

出局將是:測試

由於溢出省略號css不適用於多行文本,因此必須使用JavaScript。 您可以復制文本框,將其置於頂部-1000000px的絕對位置,並剪切文本的最后一個字母,直到該框具有正確的高度。 或者你在特定的字母數量后簡單切割這將更快但不准確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM