在IE中能够这样 var a=window.event.clientX;
但在Firefox中这样却没有办法,怎样获取一个兼容的event对象呢?
好比能够在IE中alert(event.clientX); 但在firefox这样就不行,比较妥善的作法是 var obj=window.event;//这样 //可是这个只能在ie中获得值,若是我想在firefox中得到这个obj.那么var obj=??????????//这里该怎么写呢?javascript
<script>
/*firefox*/
function __firefox(){
HTMLElement.prototype.__defineGetter__("runtimeStyle", __element_style);
window.constructor.prototype.__defineGetter__("event", __window_event);
Event.prototype.__defineGetter__("srcElement", __event_srcElement);
}
function __element_style(){
return this.style;
}
function __window_event(){
return __window_event_constructor();
}
function __event_srcElement(){
return this.target;
}
function __window_event_constructor(){
if(document.all){
return window.event;
}
var _caller = __window_event_constructor.caller;
while(_caller!=null){
var _argument = _caller.arguments[0];
if(_argument){
var _temp = _argument.constructor;
if(_temp.toString().indexOf("Event")!=-1){
return _argument;
}
}
_caller = _caller.caller;
}
return null;
}
if(window.addEventListener){
__firefox();
}
/*end firefox*/
</script>
event 兼容总结
event 在 IE 和 FF(Firefox) 中是不兼容的,现对经常使用的做个总结,以供参考,不表明全面。
1、设置事件java
IE 中要命的是不支持用 setAttribute 动态设置 onclick 等事件属性、对象属性、集合属性。因此涉及到兼容性问题,解决方法之一以下:浏览器
if (this.obj.attachEvent)
{
//IE
var eventStr = "FuncOnClick();";
this.obj.attachEvent("onclick", function(){eval(eventStr)});
}
else
{
this.obj.setAttribute("onclick", "javascript:FuncOnClick();");
}
更多方法请参见:this
2、event 对象firefox
IE 中能够直接使用 event 对象,而 FF 中则不能够,解决方法之一以下:prototype
更多方法请参见:Netscape中使用event对象。code
3、srcElement 和 target对象
在 IE 中 srcElement 表示产生事件的源,好比是哪一个按钮触发的 onclick 事件,FF 中则是 target。事件
var theEvent = window.event || arguments.callee.caller.arguments[0];
var srcElement = theEvent.srcElement;
if (!srcElement)
{
srcElement = theEvent.target;
}
更多内容请参见:IE 和 FF 中的 srcElement。ip
4、鼠标按钮键值。
- IE 认为:左键为 1,右键为 2,中键(滚轮按下)为 4。
- FF 认为:左键为 0,右键为 2,中键(滚轮按下)为 1。