兼容总结
- 如果两个都是属性,用逻辑 || 做兼容
- 如果有一个是方法,用三元做兼容
- 如果多个属性或方法,封装函数做兼容
获取class属性值的兼容
function getClass (obj){
if(obj.getAttribute("class") == null){
return (obj.getAttribute("className")
}else{
return (obj.getAttribute("class")
}
}
获取className兼容
function byClassName (className){
if(document.getElementsByClassName){
return document.getElementsByClassName(className);
}else{
var arr = [];
var ele = document.getElementsByTanName("*");
for(var i = 0; i < ele.length; i++){
if(ele[i].className == className){
arr.push(ele[i]);
}
}
return arr;
}
}
滚动高度兼容
var scrollTop = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
获取非行内样式的兼容
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getConputedStyle(obj,1)[attr];
}
获取事件Event兼容
oBtn.onclick = function(event){
event = event || window.event;
}
键盘值的兼容
function key(evt){
var e = evt || window.event
var keyvalue = e.getCode || e.charCOde || e.which;
return keyvalue;
}
阻止事件冒泡
function stop (e){
var e = e || window.event;
return e.stopPropagtion ? e.stopPropagtion() : e.cancelBubble = true;
}
阻止超链接的默认行为
oA.onclick = function (e){
var e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
事件源委托兼容
function target(evt){
var e = evt || window.event;
var target = e.target || e.srcElement;
return target;
}
获取鼠标值的兼容
function getButton(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;
}
}
}
添加事件的兼容
function addEventListener(obj,evt,fn,boo){
if(obj.addEventListener){
obj.addEventListener(evt,fn,boo);
}else{
obj.attachEvent("on" + evt , fn);
}
}
移除事件的兼容
function removeEventListener(obj,evt,fn,boo){
if(obj.removeEventListener){
obj.removeEventListener(evt,fn,boo);
}else{
obj.detachEvent("on" + evt , fn);
}
}