JSFiddle - React, Tailwind, and code Playground
by petroveg
HTML
<div id="count"></div>
<textarea id="t">Можно ввести фразу длиной в несколько тысяч символов и в зависимости от ширины textarea — в результате может быть разное количество строк. При этом количество переводов строки при таком вводе равно нулю, так как пользователь не нажимал "ввод". Я имел ввиду такую ситуацию.</textarea>
CSS
#test{
position:absolute;
left:-10000px;
top:-10000px;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
overflow:auto;
white-space:pre-wrap;
}
JavaScript
$(function () {
var div = $('<div id="test">').appendTo($(document.body)),
ta = $('#t'),
cs = getComputedStyle(ta.get(0), null),
lh = parseFloat(cs.lineHeight),
styles = {};
if (!lh) {
div.html(' ');
lh = div.get(0).clientHeight - parseInt(cs.paddingTop) - parseInt(cs.paddingBottom);
}
$([
'paddingTop',
'paddingRight',
'paddingBottom',
'paddingLeft',
'fontSize',
'fontFamily',
'lineHeight',
'transform'
]).each(function (index, property) {
styles[property] = cs[property];
});
ta.on('mouseup stroke.count', handler);
ta.trigger('stroke.count');
ta.get(0).addEventListener('DOMAttrModified', handler, false);
function handler (e) {
styles.width = ta.get(0).clientWidth;
div.html(ta.val().replace(/[\r\n]+/, '<br>')).css(styles);
$('#count').html(Math.round(div.get(0).clientHeight / lh));
}
});