解决 FireFox 下[使用event很麻烦] 的问题. |
在FireFox下编写事件 解决函数是很麻烦的事. 由于FireFox并没有 window.event . 假如要得到 event 对象,就必须要申明 工夫 解决函数的第一个参数为event. 所 认为了兼容IE与FireFox,普通的事件 解决 步骤为: btn.onclick=handle_btn_click; function handle_btn_click(evt) { if(evt==null)evt=window.event;//IE // 解决事件. } 关于 方便的程序,这不算麻烦. 但关于一些复杂的程序,某写函数 根本就不是直接与事件挂钩的.假如要把event传进该参数,那么全部的 步骤都要把event传来传去..这 几乎便是噩梦. 下面介绍一个解决这个麻烦事的 步骤,与原理. JScript中,函数的调用是有一个 func.caller 这个属性的. 例如 function A() { B(); } function B() { alert(B.caller); } 假如B被A调用,那么B.caller便是A 另外,函数有一个arguments属性. 这个属性 可以遍历函数目前执行的参数: function myalert() { var arr=[]; for(var i=0;i arr[i]=myalert.arguments[i]; alert(arr.join("-")); } alert("hello","world",1,2,3) 就能显示 hello-world-1-2-3 (arguments的个数与调用方有关,而与函数的参数定义没有任何关系) 依据这两个属性,我们 可以得到第一个函数的event对象: btn.onclick=handle_click; function handle_click() { showcontent(); } function showcontent() { var evt=SearchEvent(); if(evt&&evt.shiftKey)//假如是基于事件的调用,而且shift被按下 window.open(global_helpurl); else location.href=global_helpurl; } function SearchEvent() { func=SearchEvent.caller; while(func!=null) { var arg0=func.arguments[0]; if(arg0) { if(arg0.constructor==Event) // 假如便是event 对象 return arg0; } func=func.caller; } return null; } 这个例子 使用了SearchEvent来查找event对象. 其中 Event 是 FireFox 的 event.constructor . 在该例子运行时, SearchEvent.caller便是showcontent,然而showcontent.arguments[0]是空.所以 func=func.caller 时,func变为handle_click . handle_click 被 FireFox 调用, 固然没有定义参数,然而被调用时,第一个参数便是event,所以handle_click.arguments[0]便是event ! 针对上面的 常识,我们 可以 联合 prototype.__defineGetter__ 来实现 window.event 在 FireFox 下的实现: 下面给出一个 方便的代码.. 感兴趣的 可以补充 复制代码 代码如下: <script> if(window.addEventListener) { FixPrototypeForGecko(); } function FixPrototypeForGecko() { HTMLElement.prototype.__defineGetter__("runtimeStyle",element_prototype_get_runtimeStyle); window.constructor.prototype.__defineGetter__("event",window_prototype_get_event); Event.prototype.__defineGetter__("srcElement",event_prototype_get_srcElement); } function element_prototype_get_runtimeStyle() { //return style instead... return this.style; } function window_prototype_get_event() { return SearchEvent(); } function event_prototype_get_srcElement() { return this.target; } function SearchEvent() { //IE if(document.all) return window.event; func=SearchEvent.caller; while(func!=null) { var arg0=func.arguments[0]; if(arg0) { if(arg0.constructor==Event) return arg0; } func=func.caller; } return null; } </script> </body></html> |