0

設定されたdiv幅の があり、spanその中にテキストが含まれています。スタイリング

#web_view_container
{
    position:absolute;
    top:100px;
    left:100px;
    width:306px;
    height:202px;
    overflow:auto;  
}
.sentences
{
    font-family:Georgia, "Times New Roman", Times, serif;
    font-size:20px;
    line-height:120%;   
}

HTML

<div id="web_view_container">    
    <span class="sentences">Hello, This is last sentence This is last sentence This is last sentence This is last sentence This is last sentence.</span>
</div>

<span>さて、これが実行された行数を取得するにはどうすればよいでしょうか。

私は改行文字を使用していないことに注意してください。

var lines = $('#web_view_container').html().split("\n");  
alert(lines.length);

動作しません。

これは同じフィドルです。

フィドル

誰かがこれで私を助けてくれませんか。ありがとう :-)

4

2 に答える 2

5

スパンの高さを行の高さで割ります。このバージョンは、結果に影響を与える可能性のあるパディング、マージンなどを考慮していないことに注意してください。ただし、これはあなたの例では機能します。

// webkit line-height normal consideration thanks to mVChr
var $sent = $('.sentences'),
    lh = $sent.css('line-height'),
    ws = $sent.css('white-space');
if (lh === 'normal') {
    $sent.css('white-space', 'nowrap');
    lh = $sent.height();
    $sent.css('white-space', ws);
}
$('.lines').text(Math.ceil($('.sentences').height() / parseInt(lh, 10)));

更新されたフィドル

明示的な行の高さのないフィドル

更新:これは.height()、マージン、パディング、境界線が含まれていないため、マージンとパディングに関係なく機能します。このフィドルには大きなパディング/ボーダー/マージンがあり、行数を正しく計算します。

ここに画像の説明を入力

更新 2:Math.ceil()パーシャルは常に正しい値に切り上げる必要があるため、追加されました。フィドルが更新されました。

于 2013-08-28T19:21:08.677 に答える
1

要素のパディング、マージン、または境界線が変更された場合でも機能するソリューションを次に示します。

var textLineCount = function(el) {
    var $el = $(el),
        height,
        lineHeight,
        initWhitespace = $el.css('white-space');

    height = $el.height();
    $el.css('white-space', 'nowrap');
    lineHeight = $el.height();
    $el.css('white-space', initWhitespace);

    return Math.floor(height / lineHeight);
};

alert(textLineCount($('.sentences')[0]) + ' lines');

デモ内のさまざまな要素の幅、パディング、マージン、ボーダーの CSS を変更してみてください。

デモを見る

于 2013-08-28T19:36:01.170 に答える