日期:2014-05-16  浏览次数:20313 次

如何用類的對象的方法控制輸入文本框的大小
<form>
輸入關鍵字:
<input   type= "text "   id= "key "   name= "key "   size= "10 ">
<br>
輸入文章:
<input   type= "text "   id= "text "   name= "word "   size= "10 ">
<script   src= "se.js ">
</script>
</form>

以下是se.js
function   obj()   {
this.key=document.forms[0].key.value;
this.word=document.forms[0].word.value;
function   changeSize()
{
document.forms[0].key.size=document.forms[0].key.value.length;
document.forms[0].word.size=document.forms[0].key.word.length;
}
}
e=new   obj();
e.changeSize();

運行時說腳本有錯誤,哪裡錯了?
還有我想text框裡的文字發生變化時就調用changeSize方法,使text框的長度和裡面文字大小一樣,是不是控件的onChange事件呢?如何修改?
js裡對表單元素的引用如何簡單點?

------解决方案--------------------
<html>
<head>
<title> 变长文本框 </title>
</head>
<body>
<input type= "text " name= " " id= "text1 "/>
<script type= "text/javascript ">
var Env = function() {
};
Env.attachEvent = function(elem, eventName, callback) {
if (elem.addEventListener) { // Non-IE browsers
elem.addEventListener(eventName, callback, false);

} else if (elem.attachEvent) { // IE 6+
elem.attachEvent( 'on ' + eventName, callback);

} else { // Older browsers
var currentEventHandler = elem[ 'on ' + eventName];
if (currentEventHandler == null) {
elem[ 'on ' + eventName] = callback;
} else {
elem[ 'on ' + eventName] = function(e) {
currentEventHandler(e);
callback(e);
}
}
}
}

var ResizableTextbox = function(id) {
var text = document.getElementById(id);
Env.attachEvent(text, "keypress ", function() {
text.size = text.value.length + 1;
})
}

ResizableTextbox( "text1 ");
</script>
</body>
</html>

不过中文字就要多一点判断了