javascript - 文本区域中的换行符
问题描述
当文本溢出 ex 时,我需要添加换行符。如果文本是
wwwwwwwwwwwwwww
wwwwwwwwwwwwwww
在文本区域中
数据应与换行符。目前它显示的数据是
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww.
我需要显示在 textarea 中输入数据的确切方式。
当文本溢出时,它会移动到 textarea 中的下一行,但是当检索数据时,不会保留换行符。它只显示为单行或者有什么方法可以知道发生溢出以便可以添加新行?
解决方案
我从下面的小提琴中得到了答案,它将换行符应用于下一行 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 />");
}
推荐阅读
- java - Java NameLengthNotValidException 总是在 domainclass 中抛出
- c# - Exchange 2013 到 Exchange 2016
- android - 使用 fetch() 方法反应原生 Android - 网络请求失败错误
- php - xpath 在 php 中捕获表单动作属性
- java - 休眠版本 3.2.6;引起:org.hibernate.QueryException:无法解析属性:
- c# - 调整图像大小 HttpPostedFileBase MVC
- javascript - 定义一个依赖于时间的位置函数:
- javascript - React Context - setState 与消费者内部的 onClick
- android - 带有调试密钥库的签名生产版本
- odata - 为什么 ODATA 没有被开发人员广泛采用 RESTful 开发?