ie placeholder属性的兼容性问题解决方法

ie placeholder属性的兼容性问题解决方法

html 5 有个很棒的属性,placeholder,在鼠标聚焦到上面时候,提示文字会消失,失去焦点之后,又会出现:

但是在不支持html5的低版本的浏览器中,placeholder属性是无效的,为了解决这个问题,因此,人为的去实现placeholder属性:

代码如下:
//placeholder功能实现
var placeholder = {
add: function (el) {
if (!('placeholder' in document.createElement('input'))) {
var self = placeholder;
el.each(function (e) {
if (IsEmpty(e.value()) || e.value() == e.attr('placeholder')) {
e.value(e.attr('placeholder'));
e.css('color', 'gray');
}
else {
e.css('color', 'black');
}
});
el.bind('focus', self._onfocus);
el.bind('click', self._onfocus);
el.bind('blur', self._onblur);
el.bind('keyup', self._onkeyup);
}
},
remove: function (el) {
if (!('placeholder' in document.createElement('input'))) {
var self = placeholder;
el.unbind('focus', self._onfocus);
el.unbind('click', self._onfocus);
el.unbind('blur', self._onblur);
}
},
check: function (el) {
if (!('placeholder' in document.createElement('input'))) {
el.each(function (tar) {
if (IsEmpty(tar.value())) {
tar.value(tar.attr('placeholder'));
}
});
}
},
clear: function () {
if (!('placeholder' in document.createElement('input'))) {
$('input[type="text"]').each(function (el) {
if (el.value() == el.attr('placeholder')) {
el.value('');
}
});
$('textarea').each(function (el) {
if (el.value() == el.attr('placeholder')) {
el.value('');
}
});
}
},
_onfocus: function () {
if ($(this).value() == $(this).attr('placeholder'))
$(this).value('');
},
_onblur: function () {
if (IsEmpty($(this).value()) || $(this).value() == $(this).attr('placeholder')) {
$(this).value($(this).attr('placeholder'));
$(this).css('color', 'gray');
}
else {
$(this).css('color', 'black');
}
},
_onkeyup: function () {
if (IsEmpty($(this).value())) {
$(this).css('color', 'gray');
}
else {
$(this).css('color', 'black');
}
}
};

使用时候:

代码如下:
placeholder.add($('input[type="text"]'));
placeholder.add($('textarea'));

需要注意的是,考虑到如果input的type是password的时候,placeholder显示的是…..的属性

这种情况下,解决方法为:www.zzarea.com

给定两个输入框,

一个是text,一个为password的,

在有焦点的时候,切换为password,失去焦点的时候,切换为text用来展示placeholder属性.

代码如下:
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
var pwd = $("#pwd");
var password = $("#password");
pwd.focus(function(){
pwd.hide();
password.show().focus();
});
password.focusout(function(){
if(password.val().trim() === ""){
password.hide();
pwd.show();
}
});
});
</script>
<input type="text" id="pwd" value="请输入密码"/>
<input type="password" id="password" style="display:none;"/>

本文链接:https://www.dnwfb.com/1068.html,转载请注明出处。
0

评论0

没有账号? 注册  忘记密码?