3

私は3行のテキストでdivを持っているとしましょう。そのdivを2つに分割したいので、150文字あるとしましょう。分割したいので、単語ごとに2つの等しい部分になります。

では、もう少し説明させてください。

テキストノードは下にあります...stackoverflowwysiwygコンテナに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ピクセルの2つのdivに分割したいとします(私のブラウザによると、高さは104ピクセルです)。Cutしかし、私はそれをやりたいので、それは言葉遣いを意味するものではありません。つまり、2つの単語に分割したくないので、たとえば、Cあるdivと別の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>

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>

これを行う方法はありますか?

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

デモンストレーション

特にレシピに関して、より良い結果を得るために、ドットで分割することもできることに注意してください:

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 に答える