龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > div+css/html >

控制TextArea限制行数和字符数的方法讲解(2)

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
代码: scripttype="text/javascript" !-- 函数getLines被函数checkLimits调用来计算在TextArea使用的行数。变量lineHeight被设置成我们TextArea的样式属性line-height的数量值。

代码:

 <script type="text/javascript">
<!--

 函数getLines被函数checkLimits调用来计算在TextArea使用的行数。变量lineHeight被设置成我们TextArea的样式属性line-height的数量值。变量tr代表我们TextArea的文本,由bounding properties持有它的尺寸大小。我们将boundingHeight除以lineHeight来得到我们文本占有的行的数量。

function getLines(txtArea){
  var lineHeight = parseInt(txtArea.style.lineHeight.replace(/px/i,'));  
  var tr = txtArea.createTextRange();
  return Math.ceil(tr.boundingHeight/lineHeight);
}

 主函数checkLimits带三个参数,它将被这些事件调用:body.onload, textarea.onKeyUp, textarea.onCut, textarea.onPaste和textarea.onBlur: 

代码

myForm.myText = name of the textarea 
myForm.myChars = name of the field where we display the actual number of characters 
myForm.myLines = name of the field where we display the actual number of lines
 
function checkLimits(txtArea,countChars,countLines){

 在这个例子中,maxLines和maxChars的值来源于TextArea的可见大小,但是我们也可以选择任何一个适当的值。我们设置统计的countChars为txtArea.alue的长度,countLines为函数getLines(txtArea)的返回值。在页面的myForm.myChars 和 myForm.myLines上显示它们。我们也在页面上显示行数和字符数的限制值。

代码

var maxLines = txtArea.rows;
var maxChars = txtArea.rows * txtArea.cols; 
countChars.value = txtArea.value.length;
countLines.value = getLines(txtArea);
document.myForm.maxLines.value = maxLines;
document.myForm.maxChars.value = maxChars;

 首先,我们检查是否maxChars 或者  maxLines的限制是否达到。用户输入一新行时,在这个情况下,我们必须要缩短文本区内容,直到超出限制,通过弹出提示框,中断进一步输入。

代码

if((txtArea.value.length >= maxChars || getLines(txtArea) >= maxLines) 
    && (window.event.keyCode == 10 || window.event.keyCode == 13)) 

    while(getLines(txtArea) > maxLines) 
      txtArea.value = txtArea.value.substr(0,txtArea.value.length-2); 
    while(txtArea.value.length > maxChars) 
      txtArea.value = txtArea.value.substr(0,txtArea.value.length-2); 
    alert("chars and / or lines limit reached"); 
}

 如果输入了字符数量超过了最大允许数量,TestArea的长度会自动减少到txtArea的数量,会弹出提示框。

代码

else if(txtArea.value.length > maxChars ) 

    while(txtArea.value.length > maxChars) 
    { 
      txtArea.value = txtArea.value.substr(0,txtArea.value.length-1); 
    } 
    alert("chars limit reached"); 
}

 

同样,如果文本超过了行数的限制。也会自动减少直到等于maxLines,弹出提示框。有一件事情必须说起,限制的检查在input处理完之后,因此,片刻,一个垂直的scrollbar在会显示在浏览器上。最后一行会减少一些多余的字符。为了避免输入的丢失,我们设置txtArea的Height为((rows + 1) * lineHeight).

代码

else if (f (countLines.value > maxLines) 

    while(countLines.value > maxLines) 
    { 
      txtArea.value = txtArea.value.substr(0,txtArea.value.length-1); 
    } 
    alert("lines limit reached"); 
}

 

最后,统计更新。

 

  countChars.value = txtArea.value.length; 
  countLines.value = getLines(txtArea); 
} //--> 
</script>

 

    这些代码只在IE7.0中测试过。在一些情况下,限制行的数量也是必须的。例如,当文本存入数据库字段的时候,我们要统计字符的数量。进一步,我们利用boundingwidth限制TextArea的宽度,而不是由浏览器自动换行。

 代码: /Files/zhuqil/TALimit_demo.zip


精彩图集

赞助商链接