博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于JavaScript实现表单密码的隐藏和显示出来
阅读量:4458 次
发布时间:2019-06-08

本文共 2222 字,大约阅读时间需要 7 分钟。

 

转载: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;
}
}

这就是逻辑代码, 代码量不多. 大家在测试的时候, 注意细节就好.

转载于:https://www.cnblogs.com/runerering/p/6077765.html

你可能感兴趣的文章
使用jquery mobile 经验
查看>>
LeetCode(6) - ZigZag Conversion
查看>>
Java Web的MVC框架设计原则
查看>>
程序员,你有多特别
查看>>
OC-面向对象
查看>>
openlayers地图显示点
查看>>
python——杂货铺
查看>>
Redis分布式集群几点说道
查看>>
使用UI Automation实现自动化测试--1
查看>>
Ubuntu中VisualBox无法识别USB设备
查看>>
Python基础综合练习
查看>>
JVM参数配置 java内存区域
查看>>
《将博客搬至CSDN》
查看>>
python 防死锁机制
查看>>
python--使用递归优雅实现列表相加和进制转换
查看>>
一般邮件的针对SPF的TXT记录应该如何写?
查看>>
node.js操作mysql数据库之增删改查
查看>>
JVM检测&工具
查看>>
【语言处理与Python】8.5依存关系和依存文法\8.6文法开发
查看>>
(7)第3章的开始
查看>>