JavaScript設定input文字框只讀

admin發表於2017-03-19

有時候需要根據具體情況將文字框設定為只讀狀態,下面就是一段這樣的程式碼例項能夠實現此功能。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head> 
<script type="text/javascript"> 
function isreadonly(){ 
  var obj=document.getElementById("username"); 
  obj.setAttribute("readOnly",true); 
  obj.style.backgroundColor="#d2d2d2"; 
} 
window.onload=function(){
  var readonly=document.getElementById("readonly");
  readonly.onclick=isreadonly;
}
</script> 
<body> 
<form name="addform" method="post" action=""> 
<input type="text" id="username" name="username"> 
<input type="button" name="只讀" id="readonly" value="設定為只讀"/> 
</form> 
</body> 
</html>

點選按鈕可以將文字框設定為只讀狀態,具體可以參閱相關閱讀。

相關閱讀:

(1).setAttribute方法參閱setAttribute()函式的用法詳解一章節。 

相關文章