众所周知,IE9以下不兼容placeholder属性,因此自定义了一个jQuery插件placeHolder.js。下面为placeHolder.js的代码:
/**
* 该控件兼容IE9以下,专门针对IE9以下不支持placeholder属性所做
* Author: quranjie
* Date:2014-09-26
*/
$(function() {
// 如果不支持placeholder,用jQuery来完成
if(!isSupportPlaceholder()) {
// 遍历所有input对象, 除了密码框
$('input').not("input[type='password']").each(
function() {
var self = $(this);
var val = self.attr("placeholder");
input(self, val);
}
);
/* 对password框的特殊处理
* 1.创建一个text框
* 2.获取焦点和失去焦点的时候切换
*/
$('input[type="password"]').each(
function() {
var pwdField = $(this);
var pwdVal = pwdField.attr('placeholder');
var pwdId = pwdField.attr('id');
// 重命名该input的id为原id后跟1
pwdField.after('<input id="' + pwdId +'1" type="text" value='+pwdVal+' autocomplete="off" />');
var pwdPlaceholder = $('#' + pwdId + '1');
pwdPlaceholder.show();
pwdField.hide();
pwdPlaceholder.focus(function(){
pwdPlaceholder.hide();
pwdField.show();
pwdField.focus();
});
pwdField.blur(function(){
if(pwdField.val() == '') {
pwdPlaceholder.show();
pwdField.hide();
}
});
}
);
}
});
// 判断浏览器是否支持placeholder属性
function isSupportPlaceholder() {
var input = document.createElement('input');
return 'placeholder' in input;
}
// jQuery替换placeholder的处理
function input(obj, val) {
var $input = obj;
var val = val;
$input.attr({value:val});
$input.focus(function() {
if ($input.val() == val) {
$(this).attr({value:""});
}
}).blur(function() {
if ($input.val() == "") {
$(this).attr({value:val});
}
});
}
调用方法:
<html>
<head>
<title>替换placeholder属性 兼容IE demo</title>
<style type="text/css">
input {
height: 20px;
width: 150px;
}
</style>
<script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript" src="js/placeHolder.js" ></script>
<script type="text/javascript">
function check(){
// 打印出password的值
var passValue = $('#password').val();
alert(passValue);
return false;
};
</script>
</head>
<body>
<form action="#">
<input id="username" type="text" placeholder="请输入用户名" />
<input id="password" type="password" placeholder="请输入密码" />
<input id="confirm" type="password" placeholder="请确认密码" />
<br /><br />
<input type="submit" οnclick="return check();"/>
</form>
</body>
</html>
本代码兼容IE9以下,jQuery选择1.7.2的稳定版本,代码实现考虑到一个页面有多个password输入框的情况。
插播广告,本人想在工作之余做些兼职项目挣点外快,项目领域主要为:Android、IOS、PHP以及网站整站建设,其中尤其擅长Android、PHP和网站建设。
有意者请私信给我!非诚勿扰,谢谢!