javascript 最大行数 textarea
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22731394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Max lines textarea
提问by iCode4U
I have found some scripts that limit the lines used in a textarea like this:
我发现了一些限制 textarea 中使用的行的脚本,如下所示:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
var newLines=0;
$('#rev').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
It works fine when you hit enter and limits it to 10 .But the problem occurs when you type sentences that are so long they automatically go to a new line without the \n and when you copy paste a text, then it fails to limit the lines used.
当您按 Enter 并将其限制为 10 时它工作正常。但是当您键入的句子太长时会出现问题,它们会自动转到没有 \n 的新行,并且当您复制粘贴文本时,它无法限制使用的线路。
does anyone know how to fix this.
有谁知道如何解决这一问题。
Important: solution needs to work for a textarea
重要:解决方案需要适用于 textarea
回答by Aditya
You could try doing it using this logic:
您可以尝试使用以下逻辑进行操作:
JS :
JS:
var limit = 3; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");
textarea.onkeyup = function() {
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i].length <= spaces) continue;
var j = 0;
var space = spaces;
while (j++ <= spaces)
{
if (lines[i].charAt(j) === " ") space = j;
}
lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
lines[i] = lines[i].substring(0, space);
}
if(lines.length>limit)
{
textarea.style.color = 'red';
setTimeout(function(){
textarea.style.color = '';
},500);
}
textarea.value = lines.slice(0, limit).join("\n");
};
Here is the UPDATED DEMO
这是更新的演示
回答by webeno
Well, I couldn't figure out how to calculate the height of only the text inside a textarea, so I used a contenteditable
div instead. Hope you like this solution.
好吧,我无法弄清楚如何仅计算 textarea 内文本的高度,所以我使用了contenteditable
div 代替。希望你喜欢这个解决方案。
HTML
HTML
<div id="container">
<div id="rev" contenteditable="true"></div>
</div>
CSS
CSS
#container {
height:100px;
width:300px;
cursor:text;
border:1px solid #000
}
#rev {
line-height:20px;
outline:none
}
JS
JS
$(document).ready(function () {
$('#container').click(function() {
$('#rev').focus();
});
var limit = 3;
var lineHeight = parseInt($('#rev').css('line-height'));
$('#rev').keydown(function (e) {
var totalHeight = parseInt($('#rev').height());
var linesUsed = totalHeight / lineHeight;
if (e.keyCode == 13 && linesUsed >= limit) {
$('#rev').css('color', 'red');
return false;
} else {
$('#rev').css('color', '');
}
});
});
HERE IS A DEMO YOU CAN FIDDLE WITH
MAJOR EDIT
主要编辑
Following the OP pointing out I actually forgot to address the most important, I updated my code. I basically removed the check for the enter key and allowed the delete and backspace keys in case the text goes over the limit as follows. You may have to fiddle around with it a little to make it fit to your exact needs.
在 OP 指出我实际上忘记解决最重要的问题之后,我更新了我的代码。我基本上取消了对回车键的检查,并允许删除和退格键,以防文本超出限制,如下所示。您可能需要稍微调整一下以使其适合您的确切需求。
$(document).ready(function () {
$('#container').click(function() {
$('#rev').focus();
});
var limit = 3;
var lineHeight = parseInt($('#rev').css('line-height'));
$('#rev').keydown(function (e) {
var totalHeight = parseInt($('#rev').height());
var linesUsed = totalHeight / lineHeight;
if (linesUsed > limit) { // I removed 'e.keyCode == 13 &&' from here
$('#rev').css('color', 'red');
if (e.keyCode != 8 && e.keyCode != 46) return false; // I added this check
} else {
$('#rev').css('color', '');
}
});
// I added the following lines
$('#rev').on('paste', function () {
if (linesUsed > limit) {
$('#rev').css('color', 'red');
if (e.keyCode != 8 && e.keyCode != 46) return false;
} else {
$('#rev').css('color', '');
}
});
});
回答by NoGray
It's too much work to try to figure how many lines based on the number characters in each line and the textarea width (does the textarea have wrapping off or not? font size, different letter widths, spaces, etc...). The easiest way is to have two textareas (one visible and one not - height set to 0) with the same width and font styles and check the scroll height of the invisible textarea.
试图根据每行中的数字字符和 textarea 宽度(textarea 是否有换行?字体大小、不同的字母宽度、空格等)计算出多少行,工作量太大了。最简单的方法是拥有两个具有相同宽度和字体样式的文本区域(一个可见,一个不可见 - 高度设置为 0)并检查不可见文本区域的滚动高度。
Here is an example http://jsfiddle.net/SKYt4/1/
这是一个例子http://jsfiddle.net/SKYt4/1/
HTML
HTML
<textarea id="visible_textarea"></textarea>
<textarea id="hidden_textarea"></textarea> <!-- hidden by setting the height to 0 -->
<div id="used_lines"></div>
CSS
CSS
textarea {line-height:16px; /* line height to calculate number of lines */
width:150px; /* need to match width */}
#hidden_textarea {height:0px;
padding:0px;
border:none;
margin:0px;
opacity:0;}
JavaScript
JavaScript
$('#visible_textarea').keyup(function(){
$('#hidden_textarea').val(this.value);
// checking how many lines
var lns = Math.ceil(document.getElementById('hidden_textarea').scrollHeight / parseInt($('#hidden_textarea').css('line-height')));
if (lns > 10) {
$('#used_lines').css('color', '#ff0000');
}
else {
$('#used_lines').css('color', '');
}
$('#used_lines').html(lns+' lines');
});
$('#visible_textarea').change(function(){
$(this).keyup();
});