javascript怎么设置input框为只读

在javascript中,想要设置input框为只读,只需要使用setAttribute()方法给input元素添加只读属性--readOnly即可。
setAttribute() 方法添加指定的属性,并为其赋指定的值。
语法:
element.setAttribute(attributename,attributevalue)
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="text" /><br><br>
<input type="button" value="设为只读" id="btn" />
<script>
function my(id) {
return document.getElementById(id);
}
my("btn").onclick = function() {
my("text").setAttribute("readOnly", true);
}
</script>
</body>
</html>
【相关推荐:javascript学习教程】
javascript