转载:http://www.jb51.net/article/80326.htm
主要代码:<input type="password" name="pass" id="pwd"/>
<i state="off" id="iState" οnclick="aaa()">show</i>
<script type="text/javascript">
function aaa(){
var iState = document.getElementById("iState");
var pwd = document.getElementById("pwd");
var state = iState.getAttribute("state");
if(state === "off") {
pwd.setAttribute("type", "text");
iState.setAttribute("state", "on");
} else {
pwd.setAttribute("type", "password");
iState.setAttribute("state", "off");
}
}
</script>
下面是更详细的
为了网站的安全性,很多朋友都把密码设的比较复杂,但是如何密码不能明显示,不知道输的是对是错,为了安全起见可以把密码显示的,那么基于js代码如何实现的呢? 当用户输入时密码显示为圆点或者星号, 为了确保用户输入的正确, 用户可以点击让密码显示的按钮. 直接就先看节目效果.
界面结构, 一个外层的pass-box, 然后内层加入input 和 一个 i 标签, 且给他们加入相应的class名称.
1
2
3
4
|
<div class=
"pass-box"
>
<input type=
"password"
name=
"pass"
/>
<i state=
"off"
></i>
</div>
|
现在我们给相应的class加入相应的属性值. 在这个box里, i 需要在input之上, 所以需要给 i 一个position属性, 然后调整其top和right. 然后给其设置宽度和高度,设置其背景图片.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
.pass-box {
width: 300px;
margin: 30px auto;
position: relative;
}
.pass-box input {
border:
#cccccc 1px solid;
background-color:
#fff;
color:
#666;
padding: 10px;
width: 100%;
box-sizing: border-box;
}
.pass-box i{
display: inline-block;
width: 30px;
height: 30px;
position: absolute;
right: 5px;
top:5px;
background-image: none;
background-size: 200% 200%;
background-position: center;
}
|
这样界面效果完成. 然后给 i 加入点击事件. 在HTML结构中, 我们给了 i 一个状态, 这个作用主要是用于用户两次点击效果的判断. 点击第一次, 密码显示; 点击第二次, 密码隐藏. 重复这样的动作. 所以利用这个state来查看其状态.
重点就在于, 修改input的type属性, 显示的时候type为 text, 隐藏的时候是 password. 所以JS的逻辑处理也是比较清晰.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var
ele_pass_box = document.getElementsByTagName(
"div"
)[0];
var
ele_pass = ele_pass_box.getElementsByTagName(
"input"
)[0];
var
ele_eye = ele_pass_box.getElementsByTagName(
"i"
)[0];
ele_eye.onclick =
function
() {
var
state =
this
.getAttribute(
"state"
);
if
(state ===
"off"
) {
ele_pass.setAttribute(
"type"
,
"text"
);
ele_eye.setAttribute(
"state"
,
"on"
);
ele_eye.style.opacity = 0.2;
}
else
{
ele_pass.setAttribute(
"type"
,
"password"
);
ele_eye.setAttribute(
"state"
,
"off"
);
ele_eye.style.opacity = 1;
}
}
|
这就是逻辑代码, 代码量不多. 大家在测试的时候, 注意细节就好.