js控制密码的显示与隐藏实例

原理是建立2个input,一个type是text,一个type是password。在点击按钮时,这两input个的显示状态与val()的值在切换。

html:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8" />
 5 <title>案例测试</title>
 6 <link rel="stylesheet" href="css/all.css" />
 7 <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
 8 <script type="text/javascript" src="js/all.js"></script>
 9 
10 </head>
11 
12 <body>
13 <!-- 密码的显示与隐藏 -->
14 <div class="code">
15     <span>密码:</span><input type="password" /><input type="text" class="hide" /><a>SHOW</a>
16 </div>
17 <!-- End 密码的显示与隐藏 -->
18 </body>
19 
20 </html>

css:

1 /* 公共样式 */
2 * { padding: 0; margin: 0; list-style: none; }
3 .hide { display: none; }
4 
5 
6 /* 密码的显示与隐藏 */
7 .code { margin: 50px 0 0 100px; }
8 .code input { margin: 0 10px; padding: 10px 0 10px 10px; height: 20px; line-height: 20px; }
9 .code  a { display: inline-block; padding: 0 14px; line-height: 30px; background: #ddf; cursor: pointer; }

js:

 1 $(function(){
 2 //密码的显示与隐藏
 3     //alert('lll');
 4     $('.code a').on('click',function(){
 5         if($(this).html() == 'SHOW'){
 6             $(this).html('HIDE')
 7                    .siblings('input[type=text]').css('display','inline-block')
 8                    .siblings('input[type=password]').css('display','none')
 9                    ;
10             $(this).siblings('input[type=text]').val($(this).siblings('input[type=password]').val());
11         }else{
12             $(this).html('SHOW')
13                    .siblings('input[type=text]').css('display','none')
14                    .siblings('input[type=password]').css('display','inline-block')
15                    ;
16             $(this).siblings('input[type=password]').val($(this).siblings('input[type=text]').val());
17             
18         }
19                
20         
21     })
22     
23 })

 js也可以换成下面的代码,只不过是换了一个函数:当a被点击时,在两个function之间进行切换。

 1     $('.code a').toggle(function(){
 2         $(this).html('HIDE')
 3                .siblings('input[type=text]').css('display','inline-block')
 4                .siblings('input[type=password]').css('display','none')
 5                ;
 6         $(this).siblings('input[type=text]').val($(this).siblings('input[type=password]').val());
 7     },function(){
 8         $(this).html('SHOW')
 9                .siblings('input[type=text]').css('display','none')
10                .siblings('input[type=password]').css('display','inline-block')
11                ;
12         $(this).siblings('input[type=password]').val($(this).siblings('input[type=text]').val());
13     })
原文地址:https://www.cnblogs.com/darkterror/p/4995551.html