在html中可以使用如下代码进行兼容性编程:
<!--[if IE 8]>仅IE8可识别<![endif]-->
<!--[if lte IE 8]> IE8及其以下版本可识别<![endif]-->
<!--[if lt IE 8]> IE8以下版本可识别<![endif]-->
<!--[if gte IE 8]> IE8及其以上版本可识别<![endif]-->
<!--[if gt IE 8]> IE8以上版本可识别<![endif]-->
<!--[if IE]> 所有的IE可识别<![endif]-->
<!--[if !IE]>--除IE外都可识别<!--<![endif]-->(对ie10及以上版本可识别)
如上问题为兼容性问题的js脚本问题, 针对此类问题我们可以自己编写函数来解决此类问题:
//类似于divs = document.getElementsByClassName('mydiv');
var divs = getClassNames('mydiv' , 'div');
//判断是否能用document.getElementsByClassName,不能则通过节点查找
function getClassNames(classStr,tagName){
if (document.getElementsByClassName) {
return document.getElementsByClassName(classStr);
}else {
var nodes = document.getElementsByTagName(tagName),
ret = [];
for(i = 0; i < nodes.length; i++) {
if(hasClass(nodes[i],classStr)){
ret.push(nodes[i]);
}
}
return ret;
}
}
function hasClass(tagStr,classStr){
var arr=tagStr.className.split(/\s+/ ); //这个正则表达式是因为class可以有多个,判断是否包含
for (var i=0;i<arr.length;i++){
if (arr[i]==classStr){
return true ;
}
}
return false ;
}
最后把所有的document.getElementsByClassName()方法换成getClassNames()方法,其余类似的document.getElement方法可以按此思路解决。