首页 > 解决方案 > 文本区域中的换行符

问题描述

当文本溢出 ex 时,我需要添加换行符。如果文本是

wwwwwwwwwwwwwww

wwwwwwwwwwwwwww

在文本区域中

数据应与换行符。目前它显示的数据是

wwwwwwwwwwwwwwwwwwwwwwwwwwwwww.

我需要显示在 textarea 中输入数据的确切方式。

当文本溢出时,它会移动到 textarea 中的下一行,但是当检索数据时,不会保留换行符。它只显示为单行或者有什么方法可以知道发生溢出以便可以添加新行?

标签: javascriptjqueryhtmlcss

解决方案


我从下面的小提琴中得到了答案,它将换行符应用于下一行 http://jsfiddle.net/pH79a/218/

html

<div>
<textarea rows="5" id="myTextarea" ></textarea>
</div>
<div id="pnlPreview"></div>
<div>
<button type="button" onclick="ApplyLineBreaks('myTextarea');">Apply Line Breaks</button>
</div>

javascript

function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
    oTextarea.setAttribute("wrap", "off");
}
else {
    oTextarea.setAttribute("wrap", "off");
    var newArea = oTextarea.cloneNode(true);
    newArea.value = oTextarea.value;
    oTextarea.parentNode.replaceChild(newArea, oTextarea);
    oTextarea = newArea;
}

var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;

function testBreak(strTest) {
    oTextarea.value = strTest;
    return oTextarea.scrollWidth > nEmptyWidth;
}
function findNextBreakLength(strSource, nLeft, nRight) {
    var nCurrent;
    if(typeof(nLeft) == 'undefined') {
        nLeft = 0;
        nRight = -1;
        nCurrent = 64;
    }
    else {
        if (nRight == -1)
            nCurrent = nLeft * 2;
        else if (nRight - nLeft <= 1)
            return Math.max(2, nRight);
        else
            nCurrent = nLeft + (nRight - nLeft) / 2;
    }
    var strTest = strSource.substr(0, nCurrent);
    var bLonger = testBreak(strTest);
    if(bLonger)
        nRight = nCurrent;
    else
    {
        if(nCurrent >= strSource.length)
            return null;
        nLeft = nCurrent;
    }
    return findNextBreakLength(strSource, nLeft, nRight);
}

var i = 0, j;
var strNewValue = "";
while (i < strRawValue.length) {
    var breakOffset = findNextBreakLength(strRawValue.substr(i));
    if (breakOffset === null) {
        strNewValue += strRawValue.substr(i);
        break;
    }
    nLastWrappingIndex = -1;
    var nLineLength = breakOffset - 1;
    for (j = nLineLength - 1; j >= 0; j--) {
        var curChar = strRawValue.charAt(i + j);
        if (curChar == ' ' || curChar == '-' || curChar == '+') {
            nLineLength = j + 1;
            break;
        }
    }
    strNewValue += strRawValue.substr(i, nLineLength) + "\n";
    i += nLineLength;
}
oTextarea.value = strNewValue;
oTextarea.setAttribute("wrap", "");
document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />");

}


推荐阅读