<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>可显示隐藏密码切换的jQuery插件</title>
<style type="text/css">
*{margin:0;padding:0;}
body{font:14px Arial, sans-serif;color:#333;}
input{font-family:Arial, sans-serif;}
.login{270px;margin:40px auto 0 auto;padding:30px 40px;background-color:#f7f7f7;}
.login ul{list-style-type:none;}
.login li{padding:10px 0;overflow:hidden;}
.login .li3, .login .li5{text-align:right;font-size:12px;}
.login .li3 input{13px;height:13px;margin:0 3px 0 10px;vertical-align:middle;}
.login .submit{display:block;100%;padding:6px 0;border:0 none;color:#fff;background-color:#4d90fe;cursor:pointer;}
#email, #password{214px;padding:5px;border:1px solid #ccc;}
.forgot{color:#333;}
</style>
<script type="text/javascript" src="jquery/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="jquery/toggle-password.js"></script>
<script type="text/javascript">
$(function(){
$('#password').togglePassword({
el: '#togglePassword'
});
});
</script>
</head>
<body>
<div class="login">
<ul>
<li><span><label for="email">邮箱:</label></span><input id="email" type="text" placeholder="请输入邮箱地址" /></li>
<li><span><label for="password">密码:</label></span><input id="password" type="password"></li>
<li class="li3"><input type="checkbox" id="remember"><label for="remember">记住密码</label> <input type="checkbox" id="togglePassword"><label for="togglePassword">显示密码</label></li>
<li class="li4"><input class="submit" type="submit" value="登录"></li>
<li class="li5"><a class="forgot" href="javascript:">忘记密码?</a></li>
</ul>
</div>
</body>
</html>
toggle-password.js:
(function ($) {
$.fn.togglePassword = function( options ) {
var s = $.extend( $.fn.togglePassword.defaults, options ),
input = $( this );
$( s.el ).bind( s.ev, function() {
var flag = "password" == $( input ).attr( "type" )
//$(input).removeAttr("type");
//flag ? $( input ).attr( "type", "text" ) : $( input ).attr( "type", "password" );
flag ? $(input)[0].type = "text" : $(input)[0].type = "password";
});
};
$.fn.togglePassword.defaults = {
ev: "click"
};
}(jQuery));
注意:input的type属性无法修改和移除,要修改其属性,需要这样:$(input)[0].type = "text"
效果图:
总结:1、修改type值得方式:$("input")[0].type = "text",这样修改才行
2、 组件封装的思想:(1)函数立即执行:(function($){ //do something }(jQuery));(2)声明定义默认的default对象;(3)$.extend(default, options);完成自定义参数和方法的拓展。