事件偵聽器函式
阿新 • • 發佈:2018-12-10
maryun.Event = {
//頁面載入完成後
readyEvent:function (fn) {
if(fn==null){
fn = document;
}
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = fn;
}else{
window.onload = function () {
oldonload();
fn();
}
}
},
addEvent:function (element,type,handler) {
if (element.addEventListener){
//事件型別、需要執行的函式、是否捕獲
element.addEventListener(type,handler,false);
} else if(element.attachEvent){
element.attachEvent('on'+type,function () {
handler.call(element);
});
}else{
element['on' + type] = handler;
}
},
//移除事件
removeEvent:function (element,type,handler) {
if(element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if(element.detachEvent){
element.detachEvent('on' + type,handler);
}else{
element['on' + type] = null;
}
},
//阻止事件(主要是事件冒泡,因為IE不支援事件捕獲)
stopPropagation:function (ev) {
if(ev.stopPropagation){
ev.stopPropagation();
}else{
ev.cancelBubble = true;
}
},
//取消事件的預設行為
preventDefault:function (event) {
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
},
//獲取事件目標
getTarget:function (event) {
return event.target || event.srcElement;
},
//獲取event物件的引用,取到事件的所有資訊,確保隨時能使用event
getEvent:function (e) {
var ev = e || window.event;
if (!ev){
var c =this.getEvent.caller;
while (c){
ev = c.arguments[0];
if (ev && Event == ev.constructor){
break;
}
c = c.caller;
}
}
return ev;
}
};