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

Ste*_*ven 3 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>
Run Code Online (Sandbox Code Playgroud)

假设我想将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>
Run Code Online (Sandbox Code Playgroud)

分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>
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Den*_*ret 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);
Run Code Online (Sandbox Code Playgroud)

示范

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

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);?
Run Code Online (Sandbox Code Playgroud)

在点上分裂的示范

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

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);
Run Code Online (Sandbox Code Playgroud)

演示(不在jsfiddle.net上,因为它们似乎已经失效)