// 屬性的兼容,使用||解決
// 方法的兼容缕陕,使用if判斷解決
- event事件獲取兼容
//eve傳入?yún)?shù)
var e = eve || window.event;
注意:event需要逐層傳遞,不要疏忽外部的function
- 非行內(nèi)樣式兼容
function getStyle(ele,attr){
if(ele.currentStyle){
return ele.currentStyle[attr]; //IE
}else{
return getComputedStyle(ele,false)[attr]; //非IE
}
}
alert(getStyle(obox,"background-color"));
console.log(getStyle(obox2,"background-color"));
- 獲取按鍵ASCII碼
var eve = eve || window.event
var keyC = eve.keyCode || eve.which
- 添加事件監(jiān)聽(IE兼容)
// 封裝成函數(shù)
function addEvent(ele,type,callback){
if(ele.addEventListener){
ele.addEventListener(type,callback)
}else if(ele.attachEvent){
ele.attachEvent("on"+type,callback)
}else{
ele["on"+type] = callback;
}
}
function removeEvent(ele,type,callback){
if(ele.removeEventListener){
ele.removeEventListener(type,callback)
}else if(ele.detachEvent){
ele.detachEvent("on"+type,callback)
}else{
ele["on"+type] = null;
}
}
//removeEvent(obox,"click",fn1)
// 封裝成對(duì)象
var myEvent = {
add:function(ele,type,callback){
if(ele.addEventListener){
ele.addEventListener(type,callback)
}else if(ele.attachEvent){
ele.attachEvent("on"+type,callback)
}else{
ele["on"+type] = callback;
}
},
remove:function(ele,type,callback){
if(ele.removeEventListener){
ele.removeEventListener(type,callback)
}else if(ele.detachEvent){
ele.detachEvent("on"+type,callback)
}else{
ele["on"+type] = null;
}
}
}
- 阻止事件冒泡兼容
function stopBubble(e){
if(e.stopPropagation){
e.stopPropagation()
}else{
e.cancelBubble = true;//IE
}
}
- 目標(biāo)元素target兼容
target = e.target || e.srcElement;
- 阻止瀏覽器默認(rèn)行為兼容
function(e){
if(e.preventDefault){
e.preventDefault();
}else{
window.event.returnValue = false;
}
}