需要帮助将文本保持在3行而不管长度如何

时间:2012-07-31 15:36:09

标签: javascript jquery line-breaks lines

我需要找到一种方法,使用jQuery将文本保持在3行而不管其长度。 (或者我猜是javascript)

所以这个文字:

First Project Name Combined with First Location

插入了插片,使其看起来像这样:

First Project Name
Combined with
First Location

虽然这个文字:

Second Project Name Combined with Second Location And Text To Make This Text Area Even More Incredibly Extra Long

插入了插片,使其看起来像这样:

Third Project Name Combined with Third
Location And Text To Make This Text Area
Even More Incredibly Extra Extra Long

我假设代码将涉及计算字符数或空格数,除以3,然后在相对于分割长度的多个空格之后插入符号。不太确定如何在代码中写这个。

我已经设置了a jsFiddle我正在使用的实际代码。代码需要与第一段代码一起使用。 (这已经被一个非常棒的stackoverflow用户慷慨解决了)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

var text = 'Text to split in lines',
    lines = [],
    chunks, i;

text = text.split(' ');
chunks = Math.ceil(text.length / 3);

for ( i = 0; i < 3; i++) {
    lines.push( text.slice(i * chunks , chunks * i + chunks ).join(' ') );
}

这是小提琴:http://jsfiddle.net/sCRvm/


在这里你有in plugin format

(function($) {
    $.fn.splitToLines = function(numberOfLines) {
        return this.each(function() {

            var $this = $(this),
                lines = [],
                text, chunks, i;

            text = $this.text().split(' ');

            chunks = Math.ceil(text.length / numberOfLines);

            for ( i = 0; i < numberOfLines; i++) {
                lines.push( text.slice(i * chunks , chunks * i + chunks ).join(' ') );
            }

            $this.html( lines.join('<br />') );

        });
    };
}(jQuery));

包含此脚本后,您可以这样调用它:

$('div').splitToLines(3);

这是小提琴:http://jsfiddle.net/BguKx/1/

答案 1 :(得分:0)

注意:有可能比你建议的方法有更好的方法;如果有,我不知道,但我发布这是一种实现建议方法的方式,不一定是解决问题的最佳方法。

假设字符串存储在str

var len = str.length; // total length of the string
var breakpoint = len/3; // caching a third of it
var bp1 = -1; // location of the first <br>
var bp2 = -1; // location of the second <br>
for ( var i = 0; i < len; ++i ) // going through the entire string
{
    if ( str[i] == ' ' ) // might be a good idea to check for any whitespace character
    {
        if ( bp1 < 0 || Math.abs(breakpoint - i) < Math.abs(breakpoint - bp1) )
        { // either the first time through, or a better location for the first <br> than the previous best
            bp1 = i;
        }
        else if ( bp2 < 0 || Math.abs((bp1+breakpoint) - i) < Math.abs((bp1+breakpoint) - bp2) )
        { // either the first time after getting the first <br>, or a better location for the second <br>
            bp2 = i;
        }
    }
}
if ( bp1 > 0 && bp2 > 0 ) // found places
{
    str = str.substring(0, bp1) + '<br>' + str.substring(bp1+1, bp2) + '<br>' + str.substring(bp2+1);
}
else
{
    // didn't work; put some error checking code here?
}