如何使用JavaScript计算一行中的字符数 [英] How to count number of characters in a line using JavaScript

查看:99
本文介绍了如何使用JavaScript计算一行中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个宽度为200px,字体大小为16的div。现在我想计算可以适合一行div的字符数。我该如何计算使用JavaScript或jQuery的字符数量。

解决方案

更新:哦,我忽略了隐藏的评论。上面提到的CSS解决方案绝对是更好的工作。我的回答直接解决了计算符合一行的字符的问题。我不会删除它,因为有人可能会发现它很有用。



即使您有一条线,有一个比例字体。有两种方法 - 使用以下技巧或 CanvasRenderingContext2D measureText 方法。

  var target_width = 200; //线宽
var text ='Lorem ipsum。我想知道这个文本有多少个字符适合。';

var span = document.createElement('span');
document.body.appendChild(span);
span.style.whiteSpace ='nowrap';
//定义样式
span.style.fontFamily ='Lucida Grande';
span.style.fontSize ='14px';

var fit = text.length;
for(var i = 0; i span.innerHTML + = text [i];
if(span.clientWidth> target_width){
fit = i - 1;
休息;
}
}

document.body.removeChild(span);

// fit =文本的字符数
//你可以放在一行上


Suppose I have a div with width 200px and font-size 16. Now I want to calculate number of characters that can be fit into a line of div. How can I calculate number of character using JavaScript or jQuery.

解决方案

Update: Oh, I overlooked the hidden comment. The CSS solution posted above is definitely better for the job. My answer addresses directly the problem of counting the characters that fit on one line. I'm not going to delete it as someone might actually find it useful.

It is definitely possible to get the number of characters you can fit on one line even if you have a proportional typeface. There are two ways—either use the following trick or the measureText method of 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

这篇关于如何使用JavaScript计算一行中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆