现在的位置: 首页 > 综合 > 正文

兼容placeholder

2017年10月05日 ⁄ 综合 ⁄ 共 1960字 ⁄ 字号 评论关闭

转自:http://blog.csdn.net/quzhiyong99/article/details/39645077

quzhiyong99的博客

/**
 * 该控件兼容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" onclick="return check();"/>
</form>
</body>
</html>

抱歉!评论已关闭.