如何使用JavaScript计算一行中的字符数

Ano*_*oop 6 html javascript jquery

假设我有一个宽度为200px且字体大小为16的div.现在我想计算一个可以放入div行的字符数.如何使用JavaScript或jQuery计算字符数.

J. *_* K. 7

更新:哦,我忽略了隐藏的评论.上面发布的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
Run Code Online (Sandbox Code Playgroud)


Esa*_*ija 5

实际上我想截断 div 内的文本,以便它完全适合该 div(文本长度非常大)

你可以用 css 来做到这一点:

white-space: nowrap;
overflow:hidden;
text-overflow: ellipsis; //Doesn't work in all browsers, just adds "..."
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/46AML/

  • 谢谢,我每天都学到一些新东西 `text-overflow:ellipsis` (2认同)