javascript - 在javascript中查找字符串在设置宽度的div(没有换行符)内运行的行数

标签 javascript jquery html css string

我有一个 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);

不会工作。

这是一个 fiddle 。

FIDDLE

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

最佳答案

取跨度的高度除以行高。请注意,此版本不考虑可能影响结果的填充、边距等。不过,这适用于您的示例。

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

Updated fiddle

Fiddle without explicit line-height

更新:无论边距和填充如何,这都有效,因为 .height() 不包括边距、填充和边框。 This fiddle具有较大的填充/边框/边距,并且仍能正确计算行数。

enter image description here

更新 2: 添加了 Math.ceil(),因为部分应始终四舍五入以获得正确的值。 fiddle 已更新。

关于javascript - 在javascript中查找字符串在设置宽度的div(没有换行符)内运行的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496179/

相关文章:

javascript - Angular 2. *ngFor 问题,当我使用 Pipe 时

jquery - 关注 jQuery 自动完成结果(不一定是第一个)

javascript从html输入中获取文本并将其用作另一个html输入的值

php - PHP 可以像 jQuery 一样操作(显示/隐藏)div 元素吗?

javascript - 如何使用 jQuery 更改 SVG 形状的颜色?

javascript - 同源策略不允许读取远程资源

javascript - 在 React Table 7.1.0 中一次只能选择一行

javascript - Angular : what is the difference between '=' and '=?' while defining a scope in a directive

javascript - 没有从 ajax 得到响应,进入错误函数

javascript - 将 HTML 文件对象从一个 &lt;input type = file> 传递到另一个