IE8兼容处理
LiuYueKai opened this issue · 0 comments
LiuYueKai commented
IE8兼容处理
在日常开发过程中,对IE8的兼容处理可谓与其他浏览器都不一样,此文章讲开发过程中关于IE8兼容的处理进行总结。
针对html5元素处理
在html5中增加了新的语义化标签,开发过程中也会开始使用这类标签,但是在IE8下无法识别,解决此问题可通过引入如下js解决。
<!--[if lt IE 9]>
<script src="dist/html5shiv.min.js"></script>
<![endif]-->
下载链接如下:
http://www.bootcdn.cn/html5shiv/
IE8中不支持的属性或方法
在iuap-design框架中对IE8下不支持的部分属性/方法进行了兼容处理,可通过引入如下资源进行兼容
<!--[if lt IE 9]>
<script src="http://design.yyuap.com/static/uui/latest/js/u-polyfill.min.js"></script>
<![endif]-->
respond.js也是为了解决IE8兼容而存在的,在u-polyfill.min.js中已经将此部分代码包含进入。
部分IE8兼容代码(持续完善)
1、对Array的扩展
// 扩展trim
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");
};
}
// 扩展indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] == obj)
return i;
}
return -1;
};
}
// 扩展remove
if (!Array.prototype.remove) {
Array.prototype.remove = function(index) {
if (index < 0 || index > this.length) {
alert("index out of bound");
return;
}
this.splice(index, 1);
};
}
// 遍历数组,执行函数
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn) {
for (var i = 0, len = this.length; i < len; i++) {
fn(this[i], i, this);
}
};
}
if(!NodeList.prototype.forEach)
NodeList.prototype.forEach = Array.prototype.forEach;
2、对querySelectorAll的兼容
// IE8的querySelectorAll返回的对象不是Array也不是NodeList,不能调用forEach,因此重写此方法
if(!window['HTMLElement']){
var _querySelectorAll = Element.prototype.querySelectorAll;
Element.prototype.querySelectorAll = function(selector) {
var result = _querySelectorAll.call(this,selector);
if(!isDomElement(this)){
return result;
}
var resArr = [];
for(var i = 0;i < result.length;i++){
resArr.push(result[i]);
}
return resArr;
}
var _docquerySelectorAll = document.querySelectorAll;
document.querySelectorAll = function(selector) {
try{
var result = _docquerySelectorAll.call(this,selector);
var resArr = [];
if(result.length > 0){
for(var i = 0;i < result.length;i++){
resArr.push(result[i]);
}
return resArr;
}else{
return result;
}
}catch(e){
}
}
}
3、function的bind扩展
// 绑定环境
if(typeof Function.prototype.bind !== 'function'){
Function.prototype.bind = function(context){
var fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i ++){
args.push(arguments[i]);
}
return function(){
return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
4、获取事件target
event.target = event.target || event.srcElement;