限制文本区域中的行数

限制文本区域中的行数,第1张

限制文本区域中的行数

可能会
有所帮助(可能最好使用jQuery,onDomReady并毫不干扰地将keydown事件添加到textarea),但已在IE7和FF3中进行了测试:

<html>  <head><title>Test</title></head>  <body>    <script type="text/javascript">      var keynum, lines = 1;      function limitLines(obj, e) {        // IE        if(window.event) {          keynum = e.keyCode;        // Netscape/Firefox/Opera        } else if(e.which) {          keynum = e.which;        }        if(keynum == 13) {          if(lines == obj.rows) { return false;          }else{ lines++;          }        }      }      </script>    <textarea rows="4" onkeydown="return limitLines(this, event)"></textarea>  </body></html>

*编辑-说明:如果按下ENTER键,它将捕获按键,并且如果textarea中的行与textarea的行数相同,则不添加新行。否则,它将增加行数。

编辑#2: 考虑到人们仍然在回答这个问题,我想我会尽可能地对其进行更新以处理粘贴,删除和剪切。

<html><head>    <title>Test</title>    <style>        .limit-me { height: 500px; width: 500px;        }    </style></head><body><textarea rows="4" ></textarea><script>    var lines = 1;    function getKeyNum(e) {        var keynum;        // IE        if (window.event) { keynum = e.keyCode; // Netscape/Firefox/Opera        } else if (e.which) { keynum = e.which;        }        return keynum;    }    var limitLines = function (e) {        var keynum = getKeyNum(e);        if (keynum === 13) { if (lines >= this.rows) {     e.stopPropagation();     e.preventDefault(); } else {     lines++; }        }    };    var setNumberOfLines = function (e) {        lines = getNumberOfLines(this.value);    };    var limitPaste = function (e) {        var clipboardData, pastedData;        // Stop data actually being pasted into div        e.stopPropagation();        e.preventDefault();        // Get pasted data via clipboard API        clipboardData = e.clipboardData || window.clipboardData;        pastedData = clipboardData.getData('Text');        var pastedLines = getNumberOfLines(pastedData);        // Do whatever with pasteddata        if (pastedLines <= this.rows) { lines = pastedLines; this.value = pastedData;        }        else if (pastedLines > this.rows) { // alert("Too many lines pasted "); this.value = pastedData     .split(/rn|r|n/)     .slice(0, this.rows)     .join("n ");        }    };    function getNumberOfLines(str) {        if (str) { return str.split(/rn|r|n/).length;        }        return 1;    }    var limitedElements = document.getElementsByClassName('limit-me');    Array.from(limitedElements).forEach(function (element) {        element.addEventListener('keydown', limitLines);        element.addEventListener('keyup', setNumberOfLines);        element.addEventListener('cut', setNumberOfLines);        element.addEventListener('paste', limitPaste);    });</script></body></html>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5148714.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存