x
1
<!-- 在 HTML 中我们只需要将函数挂钩到 `onkeypress` 事件并指定我们的 textarea 不接受粘贴: -->
2
<form>
3
<p>每行具有固定字符数的 Textarea:<br />
4
<textarea cols="50" rows="10" onkeypress="return checkRows(this, event);"
5
onpaste="return false;"></textarea>
6
</p>
7
</form>
8
9
<script>
10
// 创建一个函数,将文本字段和键盘事件作为输入,并确定是否已达到任何限制。如果尚未达到限制,则允许键盘输入。
11
function checkRows(oField, oKeyEvent) {
12
var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode,
13
14
// 在这里放置每行的最大字符数:
15
nCols = 10,
16
// 在这里放置的最大行数:
17
nRows = 5,
18
19
nSelS = oField.selectionStart, nSelE = oField.selectionEnd,
20
sVal = oField.value, nLen = sVal.length,
21
22
nBackward = nSelS >= nCols ? nSelS - nCols : 0,
23
nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,
24
nRowStart = nBackward + nDeltaForw,
25
aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g),
26
nRowEnd = nSelE + nRowStart + nCols - nSelS,
27
sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
28
bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));
29
30
return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols);
31
}
32
</script>
33