JS 常用兼容
//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的兼容
function byClassName(obj,className){
if(obj.getElementsByClassName){ //支持
return obj.getElementsByClassName(className);
}else{
//获取全部
var eles = obj.getElementsByTagName(’*’);
var arr = [];
for(var i = 0,len = eles.length;i < len;i ++){
if(eles[i].className === className){
arr.push(eles[i]);
}
}
return arr;
}
}
//4. 获取非行内样式
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,1)[attr];
}
//5. 获取事件对象的兼容
function getEvent(){
return arguments[0] || window.event;
}
//6. //获取鼠标编码值的兼容
function getMouseCode(evt){
var e = evt || window.event;
if(evt){
return e.button;
}else if(window.event){
switch(e.button){
case 1 : return 0;
case 4 : return 1;
case 2 : return 2;
}
}
}
//7. 获取键盘编码值的兼容
event.keyCode || event.charCode || event.which
//8. 阻止事件冒泡的兼容
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
//9. 阻止默认行为的兼容
event.preventDefault ? event.preventDefault() : event.returnValue = false;
//10.添加事件监听器的兼容
function addEventListener(obj,event,fn,boo){
//初始化参数
boo = boo || false;
if(obj.addEventListener){ //标准
obj.addEventListener(event,fn,boo);
}else if(obj.attachEvent){ //ie
obj.attachEvent(‘on’ + event,fn);
}
}
//11. 移除事件监听器的兼容
function removeEventListener(obj,event,fn,boo){
//初始化参数
boo = boo || false;
if(obj.removeEventListener){
obj.removeEventListener(event,fn,boo);
}else if(obj.detachEvent){
obj.detachEvent(‘on’ + event,fn);
}
}
//12. 获取事件源的兼容
var target = event.target || event.srcElement;