3

我有一个 div,比如说 3 行文本。我想将该 div 拆分为两个,假设我有 150 个字符,我想将它拆分,这样我最终会得到两个相等的部分。

所以让我再解释一下:

下面是一个文本节点......它在stackoverflow所见即所得容器中有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 中。

所以我最终会得到类似的东西

第 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>

第 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>

有没有办法做到这一点?

4

1 回答 1

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

示范

请注意,为了获得更好的结果,尤其是关于配方,您还可以在 dot 上拆分:

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);​

演示与点上的分裂

现在,您可能不希望两个段落中的句子数量相同,但字符长度大致相同。然后,您可以执行以下操作:

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

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

于 2012-11-13T15:31:13.487 回答