javascript怎么设置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学习教程】

更多关于云服务器域名注册虚拟主机的问题,请访问西部数码官网:www.west.cn

赞(0)
声明:本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-62778877-8306;邮箱:fanjiao@west.cn。本站原创内容未经允许不得转载,或转载时需注明出处:西部数码知识库 » javascript怎么设置input框为只读

登录

找回密码

注册