假设我有一个宽度为200px,字体大小为16的div。现在,我想计算可以放入div行中的字符数。如何使用JavaScript或jQuery计算字符数。
最佳答案
更新:哦,我忽略了隐藏的评论。上面发布的CSS解决方案绝对是更好的选择。我的答案直接解决了计算适合一行的字符的问题。我不会删除它,因为有人可能会发现它确实有用。
即使您拥有成比例的字体,也绝对有可能获得一行上可以容纳的字符数。有两种方法-使用以下技巧或measureText
的CanvasRenderingContext2D
方法。
var target_width = 200; // line width
var text = 'Lorem ipsum. I want to know how many chars of this text fit.';
var span = document.createElement('span');
document.body.appendChild(span);
span.style.whiteSpace = 'nowrap';
// define the style
span.style.fontFamily = 'Lucida Grande';
span.style.fontSize = '14px';
var fit = text.length;
for (var i = 0; i < fit; ++i) {
span.innerHTML += text[i];
if (span.clientWidth > target_width) {
fit = i - 1;
break;
}
}
document.body.removeChild(span);
// fit = the number of characters of the text
// that you can fit on one line