这是我目前要向用户倒计时的字符数。 它可以在多个textareas上工作,我只需要更改id。
function checkTextArea(id,limit){
if (document.getElementById(id)){
var txt = document.getElementById(id).value;
if (txt.length>limit){
document.getElementById(id).value = txt.substr(0,limit);
}
len = document.getElementById(id).value.length;
if (document.getElementById('count'+id)){
document.getElementById('count'+id).innerHTML = (limit-len)+" characters remaining.";
}
}
}
这是限制textarea中可用行数的JS。
$(document).ready(function(){
var textArea = $('#foo');
var maxRows = textArea.attr('rows');
var maxChars = textArea.attr('cols');
textArea.keypress(function(e){
var text = textArea.val();
var lines = text.split('\n');
if (e.keyCode == 13){
return lines.length < maxRows;
}
else{ //Should check for backspace/del/etc.
var caret = textArea.get(0).selectionStart;
console.log(caret);
var line = 0;
var charCount = 0;
$.each(lines, function(i,e){
charCount += e.length;
if (caret <= charCount){
line = i;
return false;
}
//\n count for 1 char;
charCount += 1;
});
var theLine = lines[line];
return theLine.length < maxChars;
}
});
});
我需要将这些结合起来,以便我可以在多个textareas上使用行限制和字符数。
答案 0 :(得分:1)
http://jsfiddle.net/YevSV/ 我会把它作为一个练习让你在边缘漂亮
编辑:以防万一有人过来,这里作为参数的限制,并考虑到jQuery在添加字符之前调用回调这一事实(纯粹是化妆品,比较已经是&gt; = )
$(document).ready(function(){
applyLimiter("foo",420);
});
function applyLimiter(id,limit) {
if (document.getElementById('count'+id)){
document.getElementById('count'+id).innerHTML = limit+" characters remaining.";
}
var textArea = $('#'+id);
var maxRows = textArea.attr('rows');
var maxChars = textArea.attr('cols');
textArea.keypress(function(e){
var text = textArea.val();
var len=text.length;
if (document.getElementById('count'+id)){
document.getElementById('count'+id).innerHTML = (limit-(len+1))+" characters remaining.";
}
if (len>=limit) return false;
var lines = text.split('\n');
if (e.keyCode == 13){
return lines.length < maxRows;
}
else{ //Should check for backspace/del/etc.
var caret = textArea.get(0).selectionStart;
console.log(caret);
var line = 0;
var charCount = 0;
$.each(lines, function(i,e){
charCount += e.length;
if (caret <= charCount){
line = i;
return false;
}
//\n count for 1 char;
charCount += 1;
});
var theLine = lines[line];
return theLine.length < maxChars;
}
});
}