[英]IE8 onclick handler event
I've read most of the relevant articles in quirksmode.org but still I'm not sure about this one: 我在quirksmode.org上阅读了大部分相关文章,但我仍然不确定这个:
Making my app compatible with IE8 (fun fun fun) I encounter this issue when trying to set an onclick event to a link: 让我的应用程序与IE8兼容(有趣的乐趣)我在尝试将onclick事件设置为链接时遇到此问题:
function myClickHandler(event)
{
alert(event);
}
var link = document.getElementById("myLink");
link.onclick = myClickHandler; //first option
As opposed to: 相反:
function myClickHandler(event)
{
alert(event);
}
var link = document.getElementById("myLink");
link.onclick = function() {
myClickHandler(event); //second option
}
Using the first option, myClickHandler alerts undefined
. 使用第一个选项,myClickHandler警告
undefined
。 Using the second option alerts [object Event]
which makes me believe that the event object isn't passed by the first option to the handler. 使用第二个选项提醒
[object Event]
,这使我相信事件对象没有被第一个选项传递给处理程序。 Why is this so on IE8? IE8为何如此?
Note: Don't want to use attachEvent as I want to override a single listener during execution and onclick
seems to fit here fine. 注意:不想使用attachEvent,因为我想在执行期间覆盖单个侦听器,并且
onclick
似乎很适合。
Yes, the event object is not passed as a parameter to DOM0-style event handlers in IE <= 8. You need to get it from window.event
instead. 是的,事件对象不作为参数传递给IE <= 8中的DOM0样式事件处理程序。您需要从
window.event
获取它。 If you add a parameter called event
, in IE <= 8 this will be undefined
and references to event
within the event handler will resolve to the undefined parameter rather than window.event
. 如果添加一个名为
event
的参数,则在IE <= 8中,这将是undefined
并且事件处理程序中对event
引用将解析为undefined参数而不是window.event
。 I usually use window.event
to make this explicit in the code: 我通常使用
window.event
在代码中使其显式:
link.onclick = function(evt) {
evt = evt || window.event;
}
Once I needed to handle click events on window and work with target
property in IE8 一旦我需要在窗口上处理点击事件并在IE8中使用
target
属性
The solution that I used in my project: 我在项目中使用的解决方案:
document.onclick = function(event) {
event = event || fixEvent.call(this, window.event);
var target = event.target || event.srcElement;
var className = target.className;
// ....
};
//For IE8
// source: https://learn.javascript.ru/fixevent
function fixEvent(e) {
e.currentTarget = this;
e.target = e.srcElement;
if (e.type == 'mouseover' || e.type == 'mouseenter') e.relatedTarget = e.fromElement;
if (e.type == 'mouseout' || e.type == 'mouseleave') e.relatedTarget = e.toElement;
if (e.pageX == null && e.clientX != null) {
var html = document.documentElement;
var body = document.body;
e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
e.pageX -= html.clientLeft || 0;
e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
e.pageY -= html.clientTop || 0;
}
if (!e.which && e.button) {
e.which = e.button & 1 ? 1 : (e.button & 2 ? 3 : (e.button & 4 ? 2 : 0));
}
return e;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.