×
新网 > 建站推广 > 正文

javascript怎么设置input框为只读

  • 作者:zccc
  • 来源:网络
  • 2021-12-08 18:21:57

设置方法:1、使用“document.getElementById(id)”语句根据指定id值获取input元素对象;2、使用“input对象.setAttribute("readOnly", true)”语句给input元素添加只读样式。

设置方法:1、使用“document.getElementById(id)”语句根据指定id值获取input元素对象;2、使用“input对象.setAttribute("readOnly", true)”语句给input元素添加只读样式。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

在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学习教程】

  • 相关专题

免责声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,也不承认相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,请发送邮件至:operations@xinnet.com进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。

免费咨询获取折扣

Loading