Javascript addEventListener dispatchEvent

测试代码:
分别在嵌套的元素body,div#level1,div#level2,div#level3上附加事件,仅在chrome中测试通过。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
#level1{width:500px;height:300px;background-color:#aabb11}
#level2{width:300px;height:200px;background-color:#aabb88}
#level3{width:100px;height:100px;background-color:#aabbee}
</style>
</head>
<body>
<div id="level1">
    <div id="level2">
        <div id="level3">
        </div>
    </div>
</div>
<script>
var $ = function(el) {
    return new _$(el);    
};
var _$ = function(el) {
    this.el = (el && el.nodeType == 1)? el: document;
};
_$.prototype = {
    addEvent : function(type, fn, capture) {
        var el = this.el;
        if (window.addEventListener) {
            el.addEventListener(type, function(e) {
                fn.call(el, e);
            }, capture);
        } else if (window.attachEvent) {
            el.attachEvent("on" + type, function(e) {
                fn.call(el, e);
            });
        }
        return this;
    },
    trigger : function(eventname) {
        var el = this.el;
        if (document.createEvent) { // DOM Level 2 standard
            //Events,HTMLEvents,UIEevents,MouseEvents,MutationEvents
            var evt = document.createEvent("Events");
            //initEvent,initUIEvent,initMouseEvent,initMutationEvent
            evt.initEvent(eventname, true, true);
            el.dispatchEvent(evt);
        } else if (el.fireEvent) { // IE
            el.fireEvent('on'+eventname);
        }
        return this;
    }
};
function stopEvent(event){
    //event.preventDefault();
    //event.stopPropagation();
};
//element.addEventListener(event, function, useCapture)
//true - 事件句柄在捕获阶段执行;
//false- false- 默认。事件句柄在冒泡阶段执行;
//true:由外到内触发;false:由内向外触发。
var useCapture = false;
$(document.body).addEvent("custom1",function(e){console.log("body-custom1");stopEvent(e);},useCapture)
                            .addEvent("click",function(e){console.log("body");stopEvent(e);},useCapture);
var level1 = document.getElementById("level1");
$(level1).addEvent("custom1",function(e){console.log("level1-custom1");stopEvent(e);},useCapture)
            .addEvent("click",function(e){console.log("level1");stopEvent(e);},useCapture);
var level2 = document.getElementById("level2");
$(level2).addEvent("click",function(e){console.log("level2");stopEvent(e);},useCapture);
var level3 = document.getElementById("level3");
$(level3).addEvent("click",function(e){console.log("level3");stopEvent(e);},useCapture);

$(level3).trigger("custom1").trigger("click");
</script>
</body>
</html>

 运行结果(useCapture=true时,输出顺序相反):

level1-custom1
body-custom1
level3
level2
level1
body

 div#level3的Event Listeners(勾选Ancestors,包含自身和祖先的事件):

不勾选Ancestors,仅自身的事件:

posted @ 2016-01-08 13:26  MetaMan  阅读(1271)  评论(0编辑  收藏  举报