我們知道有的時候必須對文本輸入框的輸入長度進行限制,我們可以通過很簡單的maxlength 對Text 和 Password類型的輸入框的輸入長度進行限制,可是當我們對TextArea 使用maxlength 使用maxlength屬性的時候,我們遺憾的發現,這個屬性在textarea中是不起作用的有沒有辦法呢?答案是肯定的,有!就是使用HTC的技術,什麼是HTC??簡單的說,htc就是HTML Component,豆腐言語表達能力不強,我們看看下面的例子就可以了:
test.html:
<form method="POST">
<p><input type="text" size="30" maxlength="50" name="T1">
<textarea name="S1" rows="4" cols="30" maxlength="50" style="behavior:url(maxlength.htc)"></textarea>
</form>
大家注意到 以前很少見過 這樣的 用法: style="behavior:url(maxlength.htc)" 我們再看看下面的htc 的內容
<PUBLIC:COMPONENT id="bhvMaxlength" urn="maf:Maxlength">
<PUBLIC:PROPERTY name="maxLength" />
<PUBLIC:ATTACH event="onkeypress" handler="doKeypress" />
<PUBLIC:ATTACH event="onbeforepaste" handler="doBeforePaste" />
<PUBLIC:ATTACH event="onpaste" handler="doPaste" />
<SCRIPT language="JScript">
// Keep user from entering more than maxLength characters
function doKeypress(){
if(!isNaN(maxLength)){
maxLength = parseInt(maxLength);
var oTR = element.document.selection.createRange();
// Allow user to type character if at least one character is selected
if(oTR.text.length >= 1)
event.returnValue = true;
else if(value.length > maxLength-1)
event.returnValue = false;
}
}
// Cancel default behavior
function doBeforePaste(){
if(!isNaN(maxLength))
event.returnValue = false;
}
// Cancel default behavior and create a new paste routine
function doPaste(){
if(!isNaN(maxLength)){
event.returnValue = false;
maxLength = parseInt(maxLength);
var oTR = element.document.selection.createRange();
var iInsertLength = maxLength - value.length + oTR.text.length;
var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
oTR.text = sData;
}
}
</SCRIPT>
</PUBLIC:COMPONENT>