IE8兼容placeholder的方案
用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的方案的更多相关文章
- background-size IE8兼容方案
根据canius(http://caniuse.com/#search=background-size),background-size兼容性为IE9以及以上浏览器,如下图所示. 实例代码: < ...
- ie8兼容
最近在做ie8兼容,把遇到的问题整理了一下 1. margin:0 auto; 无法居中 解决方法:1.换成h4的文档类型 <!DOCTYPE html PUBLIC "-//W3C/ ...
- react 开发 PC 端项目(一)项目环境搭建 及 处理 IE8 兼容问题
步骤一:项目环境搭建 首先,你不应该使用 React v15 或更高版本.使用仍然支持 IE8 的 React v0.14 即可. 技术选型: 1.react@0.14 2.bootstrap3 3. ...
- H5C3--语义标签以及语义标签IE8兼容,表单元素新属性,度量器,自定义属性,dataList,网络监听,文件读取
HTML5新增标签以及HTML5新增的api 1.H5并不是新的语言,而是html语言的第五次重大修改--版本 2.支持:所有的主流浏览器都支持h5.(chrome,firefox,s ...
- 【jquery】基于 jquery 实现 ie 浏览器兼容 placeholder 效果
placeholder 是 html5 新增加的属性,主要提供一种提示(hint),用于描述输入域所期待的值.该提示会在输入字段为空时显示,并会在字段获得焦点时消失.placeholder 属性适用于 ...
- 360兼容模式==ie8 兼容模式下 span标签占位问题
ie8 兼容模式 ie8 标准渲染 应付金额 穿位 错误代码 <span class="span_em">应付金额:<em><span style=& ...
- ie8兼容圆角
ie8兼容圆角 PIE.HTC下载地址:http://css3pie.com/ 兼容ie8 代码如下: <!DOCTYPE html> <html> <head> ...
- 让ie8支持 placeholder 属性
一. ie8支持 placeholder 属性 /* * ie8支持 placeholder 属性 */ $(function(){ if( !('placeholder' in document. ...
- 使用X-UA-Compatible来设置IE8兼容模式
使用X-UA-Compatible来设置IE8兼容模式 本文向大家描述一下如何使用X-UA-Compatible来设置IE8兼容模式,X-UA-Compatible是针对IE8兼容模式,X-UA-Co ...
随机推荐
- RedHat9上安装jdk
1.先在windows下载jdk:jdk-6-dlj-linux-i586.bin 2.用ftp上传给linux下 3.chmod 777 jdk-6-dlj-linux-i586.bin 4.将jd ...
- [OSGI]Eclipse4.2 OSGI依赖Bundle
Eclipse 4.2 OSGI 依赖的Bundle: org.eclipse.osgiorg.apache.felix.gogo.runtimeorg.apache.felix.gogo.comma ...
- [jstl] forEach标签使用
在JSP的开发中,迭代是经常要使用到的操作.例如,逐行的显示查询的结果等.在早期的JSP中,通常使用Scriptlets来实现Iterator或者Enumeration对象的迭代输出.现在,通过JS ...
- 小tip:我是如何初体验uglifyjs压缩JS的
by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=2946 一.故事总有其 ...
- 多目标遗传算法 ------ NSGA-II (部分源码解析) 目标函数值计算 eval.c
这部分比较简单,具体的函数数值计算是需要调用设定的目标函数的,此部分一个不能忽略的问题是 超出限制条件的处理 , 故对此加以解释. 首先是包装函数, 核心操作调用 evaluate_ind 实现 ...
- The working copy xxxx needs to be upgraded to Subversion 1.7.
原因是我在svn是低版本时候checkout的项目 而对方用的版本比我高 然后 我运行这个项目 就要求我 更新 如果我选择 对项目进行upgrade. 当 upgrade后 我的项目就在 现有 ...
- 嵌入式 现已发展为 IT行业的主流——高薪,且人才缺乏
嵌入式 现已发展为 IT行业的主流——高薪,且人才缺乏 硅谷芯微技术中心,注重实践操作,以实际项目带学员,让学员真正学到东西,达到企业用人标准,有兴趣的,可以前来了解,给自己多一个选择的机会,可以多家 ...
- hdu 4550 卡片游戏
http://acm.hdu.edu.cn/showproblem.php?pid=4550 贪心 #include <cstdio> #include <cstring> # ...
- rabbitMQ入门
1 安装 1.1 首先 arbbitmq是用爱尔兰这种语言去编写的,所以,需要这种语言支持,那就需要下载以下几个包去安装来搭建环境 下载并安装erlang,http://www.erlang.org/ ...
- 创建组合索引SQL从1个多小时到1S的案例
select aa.acct_org, aa.loan_acct_no, aa.FUNCTIONARY, aa.cust_no, sum(dwm.pkg_tools.currcdtran(bb.INT ...