我有一个 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 。
有人可以帮我解决这个问题吗?谢谢:-)
最佳答案
取跨度的高度除以行高。请注意,此版本不考虑可能影响结果的填充、边距等。不过,这适用于您的示例。
// 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)));
Fiddle without explicit line-height
更新:无论边距和填充如何,这都有效,因为 .height()
不包括边距、填充和边框。 This fiddle具有较大的填充/边框/边距,并且仍能正确计算行数。
更新 2: 添加了 Math.ceil()
,因为部分应始终四舍五入以获得正确的值。 fiddle 已更新。
关于javascript - 在javascript中查找字符串在设置宽度的div(没有换行符)内运行的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496179/