取消事件传播 兼容ie和所有浏览器 preventDefault returnValue stopPropagation cancelBubble addEventListener attachEvent

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>事件取消</title>
    </head>
    <body>
        <div id="box">
            <button id="boxChild">boxChild</button>
        </div>
        
        <script type="text/javascript">
        //事件的取消
            var utilStopHandler = {
                cancelEvent:function(event){//取消事件
                    var event = event || window.event;
                    if(event.preventDefault){
                        event.preventDefault();
                    }else if(event.returnValue){
                        event.returnValue = false;
                    }else{
                        return false;
                    }
                },
                stopEvent:function(){//取消事件的传播
                    var event = event || window.event;
                    if(event.stopPropagation){
                        event.stopPropagation();
                    }else if(event){
                        event.cancelBubble = false;
                    }else{
                        return false;
                    }
                }
            }
            //封装自己的 句柄事件 
                var myUtilEvent = {
                    myAddHandler:function(element, eType, hanlder){//添加句柄
                        if(element.addEventListener){//ie8及之前版本外的所有浏览器支持的标准事件模型
                            element.addEventListener(eType, hanlder, false);
                        }else if(element.attachEvent){
                            element.attachEvent(eType, hanlder);//兼容ie9以下版本
                        }else{
                            element["on" + eType] = hanlder;
                        }
                    },
                    myRemoveHandler:function(element, eType, hanlder){//删除句柄
                        if(element.removeEventListener){
                            element.removeEventListener(eType, hanlder, false);
                        }else if(element.detachEvent){
                            element.detachEvent("on" + eType, hanlder);
                        }else{
                            element["on" + eType] = null;
                        }
                    }
                }
                
                var handler = function(e){
                    alert("thanks too!");
                }
            
            var box = document.getElementById("box");
            var boxChild = document.getElementById("boxChild");
            myUtilEvent.myAddHandler(box,"click", handler);
            myUtilEvent.myAddHandler(boxChild,"click", function(){
                alert("thanks!");
                utilStopHandler.stopEvent(boxChild);
            });
        </script>
    </body>
</html>

 

posted on 2016-03-24 16:50  发烧开发者  阅读(338)  评论(0编辑  收藏  举报

导航