Javascript:IE event.preventDefault 为 null 或不是对象

标签 javascript internet-explorer

我的代码在 FF/Chrome/除 IE 之外的所有设备中都可以正常工作(在 7/8 中都失败了,没有继续下去)。由于限制,我无法使用 jQuery,并且正在对 Javascript 进行硬编码。问题出在 IE 上,我收到“preventDefault 为 null 或不是对象”。希望你们中的一个人能找到答案,以下是相关代码:

添加事件方法:

function addEvent( obj, type, fn ) {  
  if ( obj.attachEvent ) {  
    obj['e'+type+fn] = fn;  
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}  
    obj.attachEvent( 'on'+type, obj[type+fn] );  
  } else  
    obj.addEventListener( type, fn, false );  
};

事件处理程序抛出错误:

function mousedown(e){  
  if(e.preventDefault){  
    e.preventDefault();  
  } else {  
    e.returnValue = false;  
    e.cancelBubble=true;  
  }
  //Processing   
};

此外,DOCTYPE 和字符集都在调用 HTML 页面上设置。任何想法,将不胜感激。该错误是在 mousedown 方法的 if 语句中抛出的。

编辑:

由于抓取 window.event 确实“修复”了主要问题,我发现问题出在代码的不同部分。基本上,我在预先放置的元素之上添加一个元素,然后将 mousedown/mousemove 事件注册到该 div。当在 <div> 上触发事件时,这就是抛出错误的地方。

这可能是由于我已将事件注册到 2

rect = document.createElement('div');  
rect.className='square';  
rect.id='chooser_rectangle';  
rect.style.left=initx+'px';  
rect.style.top=inity+'px';  

addEvent(rect,"mousemove",mousemove);  
addEvent(rect,"mousedown",mousedown);  

最佳答案

在 IE 中,事件对象不会作为第一个参数传递给事件处理程序。相反,它是一个全局变量:

function mousedown(e){
 var evt = e || window.event; // IE compatibility
 if(evt.preventDefault){  
  evt.preventDefault();  
 }else{  
  evt.returnValue = false;  
  evt.cancelBubble=true;  
 }
 //Processing   
};

关于Javascript:IE event.preventDefault 为 null 或不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3677748/

相关文章:

javascript - Text.splitText 会不好吗?

javascript - 使用嵌入式对象序列化 HTML 表单

javascript - 在 ie8 中使用 jasmine 比较数组失败

internet-explorer - IE 中的 Protractor 测试

javascript - 如何解决 Ext.js3.1.1 的 IE 问题 'parentNode' is null or not a object?

javascript - C++/CX : Defining public void at namespace scope

javascript - Popup.html 在所有选项卡中都是相同的(Chrome 扩展)

javascript - 为什么 JavaScript 中的 IF 语句允许重新声明变量

html - 我可以控制 IE 10 选择框的定位吗?

internet-explorer - CSS3 文本阴影 IE