DOM常见兼容汇总
//1. 滚动条距顶端的距离
var scroll_top = Math.floor(document.documentElement.scrollTop || document.body.scrollTop);
//2. 滚动条距左端的距离
var scroll_left = Math.floor(document.documentElement.scrollLeft || document.body.scrollLeft);
//3. byClassName
//byClassName的兼容
function byClassName(node,className){
if(node.getElementsByClassName){
//支持
return node.getElementsByClassName(className);
}else{
//不支持
var arr = [];
//获取所有的元素
var eles = node.getElementsByTagName(’*’);
//遍历所有元素
for(var i = 0,len = eles.length;i < len;i ++){
//过滤条件(元素中的className === className)
if(eles[i].className === className){
arr.push(eles[i]);
}
}
return arr;
}
}
//4. 获取非行内样式
//获取非行内样式的兼容
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,true)[attr];
//return window.getComputedStyle ? getComputedStyle(obj,1)[attr] : obj.currentStyle[attr];
}
//5. 获取事件对象的兼容
var e = arguments[0] || window.event;
//6. 获取鼠标编码值的兼容
function getMouseCode(evt){
var e = evt || window.event;
if(evt){ //标准浏览器
return e.button;
}else{ //IE浏览器
switch(e.button){
case 1 : return 0;
case 4 : return 1;
case 2 : return 2;
}
}
}
//7. onkeypress 获取键盘编码值的兼容
var key_code = event.keyCode || event.charCode || event.which
//8. 阻止事件冒泡的兼容
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
//9. 获取class属性值的兼容
function getClassValue(node){
return node.getAttribute(‘class’) ? node.getAttribute(‘class’) : node.getAttribute(‘className’);
}
//10. 阻止浏览器默认行为的兼容
event.preventDefault ? event.preventDefault() : event.returnValue = false;
//11. 添加事件监听器的兼容
function addEventListener(node,event,fn,bool){
//初始化参数
bool = bool || false; //设置默认值
if(node.addEventListener){ //标准
node.addEventListener(event,fn,bool);
}else if(node.attachEvent){
node.attachEvent(‘on’ + event,fn);
}
}
//12. 移除事件监听器的兼容
function removeEventListener(node,event,fn,bool){
bool = bool || false;
if(node.removeEventListener){
node.removeEventListener(event,fn,bool);
}else if(node.detachEvent){
node.detachEvent(‘on’ + event,fn);
}
}
//13. 获取事件源的兼容
var target = event.target || event.srcElement;