我自己找到了一个不同的解决方案:手动计算换行符。
我从这个线程修改和改进了换行符:在文本区域中找到“换行符”,它是自动换行的阿拉伯文
本 最大的区别:这个函数只检索中断的值而不应用中断,因为它使用了一个临时元素复制。
我认为它可以帮助别人!
function getApplyLineBreaks(strTextAreaId)
{
var strRawValue = $('#' + strTextAreaId).val();
var measureClone = $('#' + strTextAreaId).clone();
measureClone.attr('id', 'value_break_mess_clone');
measureClone.val('');
measureClone.css('overflow', 'hidden');
measureClone.removeAttr('onchange').removeAttr('onclick').removeAttr('onkeydown').removeAttr('onkeyup').removeAttr('onblur').removeAttr('onfocus');
measureClone.height(10);
measureClone.insertAfter('#' + strTextAreaId);
var lastScrollWidth = measureClone[0].scrollWidth;
var lastScrollHeight = measureClone[0].scrollHeight;
var lastWrappingIndex = -1;
var tolerancePixels = 5; //sollte kleiner als font-size
var addedSpace = false;
var debug_c = 0;
for (var i = 0; i < strRawValue.length; i++)
{
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
lastWrappingIndex = i;
measureClone.val(measureClone.val() + curChar);
addedSpace = false;
if (i != strRawValue.length - 1 && strRawValue.charAt(i + 1) != "\n")
{
measureClone.val(measureClone.val() + ' '); //this is only 90% zero-width breaker unnoticed
addedSpace = true;
}
if (((measureClone[0].scrollWidth - tolerancePixels) > lastScrollWidth) || ((measureClone[0].scrollHeight - tolerancePixels) > lastScrollHeight))
{
if (addedSpace)
measureClone.val(measureClone.val().substr(0, measureClone.val().length - 1));
var buffer = "";
if (lastWrappingIndex >= 0)
{
for (var j = lastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
lastWrappingIndex = -1;
}
buffer += curChar;
measureClone.val(measureClone.val().substr(0, measureClone.val().length - buffer.length));
if (curChar == "\n")
{
if (i == strRawValue.length - 1)
measureClone.val(measureClone.val() + buffer + "\n");
else
measureClone.val(measureClone.val() + buffer);
}
else
{
measureClone.val(measureClone.val() + "\n" + buffer);
}
lastScrollHeight = measureClone[0].scrollHeight;
}
else if (addedSpace)
{
measureClone.val(measureClone.val().substr(0, measureClone.val().length - 1));
}
}
var returnText = measureClone.val();
measureClone.remove();
return returnText;
}
唯一的一点:长文本速度很慢。欢迎提出优化建议。