原生js实现输入框清空和密码框显示隐藏

风信子 2021-06-25 00:16:41 674℃

效果图预览

html完整代码

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
	<title>原生js实现输入框清空和密码框显示/隐藏</title>
	<style>
	.form-item{
		margin: 10px;
	}
	</style>
</head>
<body>
	<form action="#" method="post">
		<div class="form-item">
			<b>用户登录</b>
		</div>
		<div class="form-item">
			帐号:<input type="text" name="account" id="account" />
			<a href="javascript:clear();">清空</a>
		</div>
		<div class="form-item">
			密码:<input type="password" name="password" id="password" />
			<a href="javascript:change();" id="change">显示</a>
		</div>
		<div class="form-item">
			<input type="submit" value="点击登录" />
		</div>
	</form>

	<script>
		//清空帐号文本
		function clear() {
			//获取帐号输入框元素
			var accountDom = document.getElementById("account");
			//清空输入框文本
			accountDom.value = "";
		}

		//密码框明文/密文切换
		function change() {
			//获取密码框元素
			var passwordDom = document.getElementById("password");
			//获取切换元素
			var changeDom = document.getElementById("change");
			//判断当前类型
			if (passwordDom.type == "password") {
				//切换为明文
				passwordDom.type = "text";
				//修改文本
				changeDom.innerText = "隐藏";
			} else {
				//切换为密文
				passwordDom.type = "password";
				//修改文本
				changeDom.innerText = "显示";
			}
		}
	</script>
</body>
</html>
标签: HTML, JS

非特殊说明,本博所有文章均为博主原创。