WD1X.COM - 问答一下,轻松解决,电脑应用解决专家
主板显卡CPU内存显示器
硬盘维修显卡维修显示器维修
注册表系统命令DOS命令Win8
存储光存储鼠标键盘
内存维修打印机维修
WinXPWin7Win11Linux
硬件综合机箱电源散热器手机数码
主板维修CPU维修键盘鼠标维修
Word教程Excel教程PowerPointWPS
网络工具系统工具图像工具
数据库javascript服务器
PHP教程CSS教程XML教程

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

更新时间:2014-07-01 15:53 作者:佚名点击:

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显示的是.....的属性

这种情况下,解决方法为:

给定两个输入框,

一个是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;"/>

顶一下
(0)
0%
踩一下
(1)
100%
------分隔线----------------------------
你可能感兴趣的内容