在javascript中查找字符串在设定宽度的div内(没有新的行分隔符)运行的行数

Har*_*ram 0 html javascript css string jquery

我有一个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%;   
}
Run Code Online (Sandbox Code Playgroud)

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

现在,我将如何获得这个<span>已经遇到的行数.

请注意,我没有使用新行字符等等

var lines = $('#web_view_container').html().split("\n");  
alert(lines.length);
Run Code Online (Sandbox Code Playgroud)

不行.

这是同样的小提琴.

小提琴

有人可以帮我解决这个问题.谢谢 :-)

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

更新了小提琴

小提琴没有明确的行高

更新:无论边距和填充如何,这都有效,因为.height()不包括边距,填充和边框.这个小提琴有大填充/边框/边距,仍然可以正确计算行数.

在此输入图像描述

更新2:添加Math.ceil()为部分应始终向上舍入为正确的值.小提琴已更新.