js实现登录界面
js技术实现登录界面,主要包含四个小知识点。含注释,为了方便,四个点我都写一起了,刚好组成一个登录界面
1.验证登录
2.验证密码
3.点击密码图片查看及隐藏密码
4.更换当前页面的背景图片
在这里插入代码片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录界面</title>、
<style>
#login {
/* display: flex; */
overflow: hidden;
width: 400px;
margin: 100px auto;
background-color: rgba(211, 203, 203, 0.4);
}
input {
display: inline-block;
width: 50%;
height: 30px;
padding-left: 20px;
outline: none;
margin-top: 5px;
margin-left: 10px;
}
input::placeholder {
color: brown;
}
#pwdeye {
position: relative;
}
#pwdeye img {
width: 30px;
height: 30px;
position: absolute;
right: 43%;
top: 9px;
}
button {
margin-left: 10px;
width: 50px;
height: 30px;
margin-top: 5px;
}
#changebgc {
float: right;
position: absolute;
top: 0;
right: 130px;
}
#changebgc ul {
list-style-type: none;
}
#changebgc ul li {
display: inline-block;
}
#changebgc ul li img {
width: 30px;
height: 30px;
}
</style>
</head>
<body>
<div id="login">
<div>
<input type="text" id="text" placeholder="请输4-10位用户名">
<span id="textadd"></span>
</div>
<div id="pwdeye">
<input type="password" name="" id="pwd" placeholder="请输入6-10位密码">
<img src="images/closeeye.png" alt="">
<span id="pwdadd"></span>
</div>
<button>登录</button>
</div>
<div id="changebgc">
<ul>
<li><img src="images/bg5.png" alt=""></li>
<li><img src="images/ceb5.jpg" alt=""></li>
<li><img src="images/ceb6.jpg" alt=""></li>
</ul>
</div>
<script>
//效果:对用户名、密码输入进行验证,并且在span处显示出错误信息;点击密码图片查看密码,再点击图片,隐藏密码;点击图片,更换当前页面背景
// 1.获取事件源——用户名 密码 span 密码图片 背景图片 当前页面
var text = document.getElementById('text');
var pwd = document.getElementById('pwd');
var textadd = document.getElementById('textadd');
var pwdadd = document.getElementById('pwdadd');
var img = document.querySelector('img');
var bgcimg = document.getElementById('changebgc').querySelectorAll('img');
var body = document.body;
// 注册事件 处理程序
// 1.用户名验证
text.oninput = function () {
if (text.value.length < 4 || text.value.length > 10) {
textadd.innerHTML = '输入错误';
textadd.style.color = 'red';
} else {
textadd.innerHTML = '输入正确';
textadd.style.color = 'green';
}
}
//2.密码验证
pwd.oninput = function () {
if (pwd.value.length < 4 || pwd.value.length > 10) {
pwdadd.innerHTML = '输入错误';
pwdadd.style.color = 'red';
} else {
pwdadd.innerHTML = '输入正确';
pwdadd.style.color = 'green';
}
}
//一张图片标记两个状态,先设置一个状态标记量
//注意标记变量需要放在事件外,否则两个状态只能显示出一个状态
var flag = 0;
//3.查看密码
img.onclick = function () {
if (flag == 0) {
img.src = 'images/eye.png';
pwd.type = 'text';
flag = 1;
} else {
img.src = 'images/closeeye.png';
pwd.type = 'password';
flag = 0;
}
}
//4.更换背景图片
for (var j = 0; j < bgcimg.length; j++) {
bgcimg[j].onclick = function () {
for (var i = 0; i < bgcimg.length; i++) {
body.style.backgroundImage = 'url(' + this.src + ')';
}
}
}
</script>
</body>
</html>