jQuery / Javascript将文本节点分成两个或三个?

时间:2012-11-13 15:27:21

标签: javascript jquery

我有一个div让我们说3行文字。我想把那个div分成两个,所以假设我有150个字符,我想把它分开,这样我最终会有两个相同的部分。

让我再解释一下:

文本节点在下面......它在stackoverflow wysiwyg容器中有6行:

<p>Brown the roast on all sides in a large lightly oiled skillet over high heat, before 
adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring 
potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length. 
Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on 
top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover 
and cook on low for 8-10 hours. Yield: 6 servings.</p>

假设我想将该div分成两个52像素的div(根据我的浏览器,它的高度为104像素)。但我想这样做,所以它并不意味着措辞,这意味着我不想将Cut分成两个单词,所以C在一个div中,ut在另一个div中,例如。

所以我最终会得到像

这样的东西

Div 1

<p>Brown the roast on all sides in a large lightly oiled skillet over high heat, before 
    adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring 
    potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length. </p>

Div 2

<p>Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on 
    top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover 
    and cook on low for 8-10 hours. Yield: 6 servings.</p>

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:6)

您可以使用

var text = $('div').text();
var tokens = text.split(' ');
var n = Math.floor(tokens.length/2);
var html = '<p>'+tokens.slice(0, n).join(' ') + '</p><p>' + tokens.slice(n+1, tokens.length).join(' ') + '</p>';
$('div').html(html);

Demonstration

请注意,为了获得更好的结果,特别是在食谱方面,您还可以在点上分割:

var text = $('#a').text();
var tokens = text.split('.');
var n = Math.floor(tokens.length/2);
var html = '<p>'+tokens.slice(0, n).join('.') + '.</p><p>' + tokens.slice(n+1, tokens.length).join('.') + '</p>';
$('#a').html(html);​

Demonstration with a split on the dot

现在,您可能不希望在两个段落中使用相同数量的句子,但字符长度大致相同。然后,这是你可以做的:

var text = $('#a').text();
var sentences = text.split('.');
var sum = 0;
var lengths = sentences.map(function(v){sum+=v.length; return v.length});
var n = 0;
var ts = 0;
while (ts<sum/2) ts += lengths[n++];
var html = '<p>'+sentences.slice(0, n-1).join('.') + '.</p><p>' + sentences.slice(n, sentences.length).join('.') + '</p>';
$('#a').html(html);

Demonstration(不在jsfiddle.net上,因为它们似乎已关闭)