用JavaScript解决Placeholder的IE8兼容问题

placeholder属性是HTML5新添加的属性,当input或者textarea设置了该属性后,该值的内容将作为灰色提示显示在文本框中,当文本框获得焦点时,提示文字消失,placeholder可作为输入框的提示文案

如图:

placeholder是常用的属性,它使得input框内有很友好的提示效果。高版本浏览器都支持placeholder属性,但IE9以下版本的浏览器并不支持这一属性。这里用JavaScript实现添加对浏览器的兼容处理。

方案一:jquery实现

(当浏览器不支持placeholder属性时,克隆一个和界面相同的input框,将placeholder的值设置为其value值,覆盖在界面input框所在位置,并将界面上的input隐藏掉)

调用方法: $(#selector).placeholder();(selector泛指css 的 id选择器)

(这里有一个问题,当文本框type=password时,引用此placeholder方案会使暗文密码变成明文密码)

 ;(function(window, document, $) {

     // Opera Mini v7 doesn’t support placeholder although its DOM seems to indicate so
var isOperaMini = Object.prototype.toString.call(window.operamini) == '[object OperaMini]';
var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
var prototype = $.fn;
var valHooks = $.valHooks;
var propHooks = $.propHooks;
var hooks;
var placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() {
return this;
}; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
}; placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported; hooks = {
'get': function(element) {
var $element = $(element); var $passwordInput = $element.data('placeholder-password');
if ($passwordInput) {
return $passwordInput[0].value;
} return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element); var $passwordInput = $element.data('placeholder-password');
if ($passwordInput) {
return $passwordInput[0].value = value;
} if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != safeActiveElement()) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
}; if (!isInputSupported) {
valHooks.input = hooks;
propHooks.value = hooks;
}
if (!isTextareaSupported) {
valHooks.textarea = hooks;
propHooks.value = hooks;
} $(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
}); // Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
}); } function args(elem) {
// Return an object of element attributes
var newAttrs = {};
var rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
} function clearPlaceholder(event, value) {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
} function setPlaceholder() {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
} function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (exception) {}
} }(this, document, jQuery));

方案二: js/jQuery实现

实现思路:

1、首先判断浏览器是否支持placeholder属性,如果不支持则使用模拟placeholder

2、创建一个label标签:<label>密码</label> 标签里面的内容为所要添加的提示文字,该文字应该从对应的input|textarea标签取得其placeholder属性值,再将label标签遮盖 到所对应的input|textarea上

3、代码实现如下:

 ; (function (win) {

     win.isPlaceholer = function () {
var input = document.createElement("input");
return "placeholder" in input;
}; win.placeholder = function () { if (!isPlaceholer()) {
var Placeholder =function (obj) {
this.input = obj;
var te = obj.getAttribute('placeholder');
this.label = document.createElement('label');
this.label.innerHTML = te;
this.label.id = obj.id + 'Label';
this.label.style.cssText = 'position:absolute; text-indent:4px;color:#999999; font-size:14px;';
if (obj.value !== '') {
this.label.style.display = 'none';
}
this.init();
};
Placeholder.prototype = { getxy: function (obj) {
var left, top;
if (document.documentElement.getBoundingClientRect) {
var html = document.documentElement,
body = document.body,
pos = obj.getBoundingClientRect(),
st = html.scrollTop || body.scrollTop,
sl = html.scrollLeft || body.scrollLeft,
ct = html.clientTop || body.clientTop,
cl = html.clientLeft || body.clientLeft;
left = pos.left + sl - cl;
top = pos.top + st - ct;
} else {
while (obj) {
left += obj.offsetLeft;
top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return {
left: left,
top: top
};
}, getwh: function (obj) {
return {
w: obj.offsetWidth,
h: obj.offsetHeight
};
}, setStyles: function (obj, styles) {
for (var p in styles) {
obj.style[p] = styles[p] + 'px';
}
},
init: function () {
var label = this.label,
input = this.input,
getXY = this.getxy,
xy = this.getxy(input),
wh = this.getwh(input);
this.setStyles(label, { 'width': wh.w, 'height': wh.h, 'lineHeight': 40, 'left': xy.left + 8, 'top': xy.top });
document.body.appendChild(label);
label.onclick = function () {
this.style.display = "none";
input.focus();
};
input.onfocus = function () {
label.style.display = "none";
};
input.onblur = function () {
if (this.value === "") {
label.style.display = "block";
}
};
if (window.attachEvent) {
window.attachEvent("onresize", function () {
var xy = getXY(input);
Placeholder.prototype.setStyles(label, { 'left': xy.left + 8, 'top': xy.top });
});
} else {
window.addEventListener("resize", function () {
var xy = getXY(input);
Placeholder.prototype.setStyles(label, { 'left': xy.left + 8, 'top': xy.top });
}, false);
}
}
}; var inpColl = $("#Box input:visible");//这里是页面上要添加placeholder支持的input
//var inpColl = document.getElementsByTagName('input'),
var textColl = document.getElementsByTagName('textarea');//这里是页面上要添加placeholder支持的textarea
//var lableArr = $("#Box lable");
var toArray = function (coll) {
for (var i = 0, a = [], len = coll.length; i < len; i++) {
a[i] = coll[i];
}
return a;
};
var inpArr = toArray(inpColl),
textArr = toArray(textColl), placeholderArr = inpArr.concat(textArr);
for (var i = 0; i < placeholderArr.length; i++) {
if (placeholderArr[i].getAttribute('placeholder') !== null) { new Placeholder(placeholderArr[i]);
}
}
} };
}(window));

方法执行后界面代码:(lable在页面上)

IE8效果图如下:

IE8兼容placeholder的方案的更多相关文章

  1. background-size IE8兼容方案

    根据canius(http://caniuse.com/#search=background-size),background-size兼容性为IE9以及以上浏览器,如下图所示. 实例代码: < ...

  2. ie8兼容

    最近在做ie8兼容,把遇到的问题整理了一下 1. margin:0 auto; 无法居中 解决方法:1.换成h4的文档类型 <!DOCTYPE html PUBLIC "-//W3C/ ...

  3. react 开发 PC 端项目(一)项目环境搭建 及 处理 IE8 兼容问题

    步骤一:项目环境搭建 首先,你不应该使用 React v15 或更高版本.使用仍然支持 IE8 的 React v0.14 即可. 技术选型: 1.react@0.14 2.bootstrap3 3. ...

  4. H5C3--语义标签以及语义标签IE8兼容,表单元素新属性,度量器,自定义属性,dataList,网络监听,文件读取

    HTML5新增标签以及HTML5新增的api     1.H5并不是新的语言,而是html语言的第五次重大修改--版本     2.支持:所有的主流浏览器都支持h5.(chrome,firefox,s ...

  5. 【jquery】基于 jquery 实现 ie 浏览器兼容 placeholder 效果

    placeholder 是 html5 新增加的属性,主要提供一种提示(hint),用于描述输入域所期待的值.该提示会在输入字段为空时显示,并会在字段获得焦点时消失.placeholder 属性适用于 ...

  6. 360兼容模式==ie8 兼容模式下 span标签占位问题

    ie8 兼容模式 ie8 标准渲染 应付金额 穿位 错误代码 <span class="span_em">应付金额:<em><span style=& ...

  7. ie8兼容圆角

    ie8兼容圆角 PIE.HTC下载地址:http://css3pie.com/ 兼容ie8 代码如下: <!DOCTYPE html> <html> <head> ...

  8. 让ie8支持 placeholder 属性

    一.  ie8支持 placeholder 属性 /* * ie8支持 placeholder 属性 */ $(function(){ if( !('placeholder' in document. ...

  9. 使用X-UA-Compatible来设置IE8兼容模式

    使用X-UA-Compatible来设置IE8兼容模式 本文向大家描述一下如何使用X-UA-Compatible来设置IE8兼容模式,X-UA-Compatible是针对IE8兼容模式,X-UA-Co ...

随机推荐

  1. js学习笔记之:时间(三)

    今天来学习一个简单的时间应用:时间的倒影,如图所示:   主要知识点: 1  获取系统的时间值:2 建立一个div的倒影 div的倒影主要利用css来控制,函数值为:filter:flipv() 步骤 ...

  2. 关于Chrome(谷歌浏览器)对docume,准确获取网页客户区的宽高、滚动条宽高、滚动条Left和Top

    对于document.compatMode,很多朋友可能都根我一样很少接触,知道他的存在却不清楚他的用途.今天在ext中看到 document.compatMode的使用,感觉这个对于我们开发兼容性的 ...

  3. 习题二:string数组应用

    说明: 读字符串char buf[100]="xxx:yyy:zzz:aaa:bbb" 按“:”进行分解到string数组中去 逻辑: 通过指针遍历整个字符串 遇到'\0'表示字符 ...

  4. IOS 性能优化的建议和技巧

    IOS 性能优化的建议和技巧 本文来自iOS Tutorial Team 的 Marcelo Fabri,他是Movile的一名 iOS 程序员.这是他的个人网站:http://www.marcelo ...

  5. java的占位符

    java占位符的类型: 常规类型的格式化 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得C语言的sprintf()方法,两者有类似之处.fo ...

  6. maven学习心得

    心得:这几天一直在研究maven的配置,还真是伤心啊,网上资料不多,而且问题不断.确实很让人头疼 背景:之所以学习maven是因为我们需要一键部署,我们项目是已经差不多完成了,是eclipse的web ...

  7. 哎,就硬盘还不是最掉价的,1999的自配主机,VIRTUALBOX里虚拟机,聊以自慰吧。

    安装时注意的问题,要是不测试MYSQL,则CONFIGURE参数和DISABLE-MYSQL,在编译时有提示的. 然后就是LIBTOOL包过老的问题,以及未安装LIBTOOL包的问题. 最后,是运行命 ...

  8. -_-#【Canvas】

    context.lineWidth = 0.5 incorrect display lineWidth=1 at html5 canvas canvas.save() canvas.restore() ...

  9. J - Borg Maze - poj 3026(BFS+prim)

    在一个迷宫里面需要把一些字母.也就是 ‘A’ 和 ‘B’连接起来,求出来最短的连接方式需要多长,也就是最小生成树,地图需要预处理一下,用BFS先求出来两点间的最短距离, *************** ...

  10. HTTP学习笔记3-响应结构

    HTTP响应: 13,在接收和解释请求消息后,服务器会返回一个HTTP响应消息. 14,与HTTP请求类似,HTTP响应也是由三个部分组成,分别是:状态行.消息报头.响应正文. 15,状态行由协议版本 ...