大家好,我是林译川,今天我们来聊一聊如何在网页上实现密码显示与隐藏的效果。
在日常生活中,我们经常需要在网页上输入密码,有时候我们希望密码是可见的,有时候又希望它是隐藏的。今天,我就来教大家如何用HTML、CSS和JavaScript来实现这个功能。
实现步骤
首先,我们需要定义HTML结构,包括一个输入框和一个控制显示与隐藏的按钮:
<div class="kuang">
<input type="password" placeholder="请输入密码......" id='password' >
<div class="conceal" id='conceal'></div>
</div>
接下来,我们定义CSS样式,包括输入框和按钮的基本样式:
.kuang{
position: relative;
width: 380px;
height: 60px;
border-radius: 5px;
box-shadow: inset 5px 5px 10px rgba(204, 197, 197,.5),
inset -5px -5px 8px rgba(204, 197, 197,.5);
}
.kuang input{
position: absolute;
top: 0;
left: 20px;
height: 100%;
width: 300px;
font-size: 18px;
outline: none;
border: none;
background-color:transparent;
}
.kuang input::placeholder{
color: rgba(68, 67, 67,.8);
}
.conceal{
position: absolute;
top: 15px;
right: 15px;
width: 30px;
height: 30px;
background-image: url(mima/xianshi.png);
background-size: 100% 100%;
cursor: pointer;
}
.conceal.yincang{
background-image: url(mima/yincang.png);
background-size: 100% 100%;
}
最后,我们用JavaScript来实现点击按钮时切换密码的显示与隐藏状态:
var password = document.getElementById('password');
var anniu = document.getElementById('conceal');
anniu.addEventListener('click',function(){
if(password.type==='password')
{
password.setAttribute('type','text');
anniu.classList.add('yincang');
}else{
password.setAttribute('type','password');
anniu.classList.remove('yincang');
}
})
这样,我们就完成了密码显示与隐藏效果的实现。希望这篇文章能帮助到大家。
如果你对编程还有其他疑问,欢迎访问「新派编程网」(www.xjpbg.com)了解更多内容。
我是林译川,我们下期再见!
