表单密码强度验证(demo)
思路:
布局写好之后我们先拿到所有需要用的元素
根据密码安全强度我们写3个正则表达式
为密码输入框添加一个事件监听器,事件类型为keyup键盘抬起
当我抬起的时候 就获取一次当前的输入内容并且判断
在判断的时候因为我们需要有一个级别的限制 所以声明一个flag表示开关
首先判断是否满足一级强度 因为满足后只显示一个提示块 所以不用判断flag 满足就改变提示一级框的颜色 不满足给flag赋值为false
然后判断是否满足二级强度 因为满足后后需要一级提示块也亮着所以要拿到一级判断后的flag的值 同时满足二级正则 和flag为true 就让二级提示块亮
然后判断是否满足三级强度 因为满足后后需要一 二级提示块也亮着所以要拿到一级和二级判断后的flag的值 同时满足三级正则 和flag为true 就让三级提示块亮
<script>
let inp = document.querySelector('input')
let sp1 = document.querySelectorAll('span')[0]
let sp2 = document.querySelectorAll('span')[1]
let sp3 = document.querySelectorAll('span')[2]
// 密码纯数字 为弱 一级强度
let numReg = /\d{6,}/
// 密码有数字字母 为中 二级强度
let leater = /[a-zA-Z]{2,}/
// 密码中有数字字母 特殊符号 为强
let underline = /[_&%#@]{1,}/ 三级强度
inp.addEventListener(‘keyup’,function(){
let flag = false // 默认是不满足
let pas_value = inp.value
以下if判断只要输入框的值满足正则判断就改变flag 的值
同时中级 和 高级 都需要判断flag值 都满足的情况下再改变提示块的颜色
if(numReg.test(pas_value)===true){
sp1.style.backgroundColor=‘red’
flag=true 此时的flag表示 一级强度满足 所以我可以进行二级判断
}else{
sp1.style.backgroundColor=’’
flag = false 此时的flag表示 一级不满足 我不能让二级判断 所以我变成false
}
if(leater.test(pas_value)===true&&flag===true){
sp2.style.backgroundColor='red'
flag=true 此时的flag表示 二级强度满足 所以我可以进行三级判断
}else{
sp2.style.backgroundColor=''
flag = false 此时的flag表示 二级不满足 我不能让三级判断 所以我变成false
}
if(underline.test(pas_value)===true&&flag===true){
sp3.style.backgroundColor='red'
}else{
sp3.style.backgroundColor=''
}
})
</script>
这是布局:
<style>
span{
display: inline-block;
width: 50px;
height: 20px;
text-align: center;
border: 1px solid black;
margin-left: 20px;
margin-top: 10px;
}
</style>
Password:<input type="text"><br>
<span>弱</span>
<span>中</span>
选项卡案例
思路:就是当我们点击不同按钮的时候执行过程为 先把所有的效果类名取消 然后让我当前点击的这个按钮和显示块 加上效果类名
js:
let btn = document.querySelectorAll('ul>li') //获取按钮元素 用于每次点击
let txt = document.querySelectorAll('ol>li') //获取显示区元素, 每次点击后对应的显示块出现
for(let i = 0;i<btn.length;i++){ //遍历所有的按钮元素
btn[i].addEventListener('click',function(){ //为所有的按钮元素添加事件监听器
for(let j = 0;j<btn.length;j++){ //取消所有按钮和显示块的类名
btn[j].className=''
txt[j].className=''
}
this.className='btn_active' //让我当前点击的这个按钮类名为btn_active
txt[i].className='txt_active' //让我当前点击的这个按钮类名为txt_active
})
}
<style>
li{
list-style: none;
}
*{
margin: 0;
padding: 0;
}
div{
width: 400px;
height: 300px;
border: 1px solid skyblue;
}
ul{
width: 100px;
height: 100%;
float: left;
background-color: turquoise;
}
ul li{
width: 100%;
height: 50px;
text-align: center;
font-size: 50px;
line-height: 50px;
background-color: slateblue;
margin-top: 10px;
cursor: pointer;
}
/* ul li:hover{
background-color: springgreen;
} */
ol{
width: 300px;
float: left;
height: 100%;
position: relative;
}
ol li{
width: 100%;
height: 100%;
position: absolute;
text-align: center;
font-size: 50px;
line-height: 300px;
display: none;
background-color: tomato;
}
.btn_active{
background-color: yellow;
}
.txt_active{
display: block;
}
</style>
<div>
<ul>
<li class="btn_active">1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="txt_active">1</li>
<li>2</li>
<li>3</li>
</ol>