1

我需要找到一种使用 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,然后在相对于分割长度的这么多空格之后插入中断。虽然不太确定如何用代码编写它。

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

有任何想法吗?

4

2 回答 2

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/


在这里,您可以使用插件格式

(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/

于 2012-07-31T15:48:04.953 回答
0

Note: it's possible that there is a better approach to this than the one you've suggested; if there is, I don't know it, but I'm posting this as a way to achieve your suggested approach, not necessarily as the best way to solve the problem.

Assumes that the string is stored in 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?
}
于 2012-07-31T15:46:23.277 回答