Kub*_*ský 2 html javascript jquery
我需要一些可以计算行数的函数(我知道在 stackoverflow 上有超过数百个这样的问题)但在我的情况下,即使没有行尾(意思是“/n”),我也需要计算它们,因为典型的函数是
textarea.value.substr(0, textarea.selectionStart).split("\n").length;.
Run Code Online (Sandbox Code Playgroud)
这意味着如果用户溢出行的最大长度但他不使用“输入”并且文本在“新行”上。好吧,我不知道如何更好地描述它,所以在fiddle https://jsfiddle.net/fNPvf/12872/上有一个例子
尝试写出没有空格、输入等的长句。你就会看到问题出在哪里
我真正不想要的是 css 规则 nowrap、overflow-x 等。
干得好。
/** @type {HTMLTextAreaElement} */
var _buffer;
/**
* Returns the number of lines in a textarea, including wrapped lines.
*
* __NOTE__:
* [textarea] should have an integer line height to avoid rounding errors.
*/
function countLines(textarea) {
if (_buffer == null) {
_buffer = document.createElement('textarea');
_buffer.style.border = 'none';
_buffer.style.height = '0';
_buffer.style.overflow = 'hidden';
_buffer.style.padding = '0';
_buffer.style.position = 'absolute';
_buffer.style.left = '0';
_buffer.style.top = '0';
_buffer.style.zIndex = '-1';
document.body.appendChild(_buffer);
}
var cs = window.getComputedStyle(textarea);
var pl = parseInt(cs.paddingLeft);
var pr = parseInt(cs.paddingRight);
var lh = parseInt(cs.lineHeight);
// [cs.lineHeight] may return 'normal', which means line height = font size.
if (isNaN(lh)) lh = parseInt(cs.fontSize);
// Copy content width.
_buffer.style.width = (textarea.clientWidth - pl - pr) + 'px';
// Copy text properties.
_buffer.style.font = cs.font;
_buffer.style.letterSpacing = cs.letterSpacing;
_buffer.style.whiteSpace = cs.whiteSpace;
_buffer.style.wordBreak = cs.wordBreak;
_buffer.style.wordSpacing = cs.wordSpacing;
_buffer.style.wordWrap = cs.wordWrap;
// Copy value.
_buffer.value = textarea.value;
var result = Math.floor(_buffer.scrollHeight / lh);
if (result == 0) result = 1;
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果我正确理解这个问题,你需要计算两件事。
这是一些伪代码:
var lineLengthLimit = 40;
var lineCounter = 0;
foreach(lines as line){
lineCounter+=Math.floor(line.length/lineLengthLimit);
}
lineCounter += lines.length;
Run Code Online (Sandbox Code Playgroud)
另一个选择可能是这个人建议的: https: //stackoverflow.com/a/3697249/1207539,但它似乎有点粗略。
| 归档时间: |
|
| 查看次数: |
2448 次 |
| 最近记录: |