问题描述
Firefox缺少window.event ...让我措手不及...
I have been caught off guard by Firefox's lack of window.event ... namely
<script>
function clicked()
{
console.log(event);
}
</script>
<div onclick = "clicked()">Whatever</div>
几乎可以在所有现代浏览器中使用,但是事件"在Firefox中是未定义的,我们必须在其中明确编写
will work in pretty much every modern browser, yet "event" will be undefined in Firefox, where we have to explicitly write
<script>
function clicked(event)
{
console.log(event);
}
</script>
<div onclick = "clicked(event)">Whatever</div>
是否有可行的解决方法来访问Firefox中的事件对象,而不必将其明确声明为功能参数?
Is there any viable workaround to access the event object in Firefox without having to make it explicit as a function parameter?
推荐答案
这是一个丑陋的骇客,它基于所有事件侦听器最终都将由 EventTarget.addEventListener()
方法.下面的解决方案"更改了 EventTarget
的原型(很糟糕!),以便将所有事件侦听器包装在一种方法中,该方法将事件分配给 window.event
,然后再委派给实际的听众.
Here's an ugly hack, based on the assumption that all event listeners will ultimately be registered by the EventTarget.addEventListener()
method. The "solution" below changes EventTarget
's prototype (yuck!) so as to wrap all event listeners in a method that will assign the event to window.event
before delegating to the actual listener.
const addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(name, handler) {
addEventListener.call(this, name, function(event) {
window.event = event;
handler(event);
})
};
function clicked() {
// just demonstrating that window.event is set
console.log(window.event.target.innerHTML);
}
document.getElementById('one').addEventListener('click', clicked);
document.getElementById('two').addEventListener('click', clicked);
<button id="one">Test 1</button>
<button id="two">Test 2</button>
以上内容仅说明了一种可能的方法,并且未经测试.您的里程可能会有所不同.
The above just illustrates a possible approach and is largely untested. Your mileage may vary.
更新
正如注释中指出的那样,这不适用于通过 on ...
HTML属性绑定或使用 Element.on ...
分配的事件处理程序.属性.
As pointed out in the comments, this will not work for event handlers bound through the on...
HTML attributes or assigned using the Element.on...
properties.
另一种(可能是更安全的)方法可能是在文档元素上使用事件捕获,然后在其中执行对 window.event
的分配.
An alternative (and arguably safer) approach could be to use event capturing on the document element, and perform the assignment to window.event
there.
document.documentElement.addEventListener('click', function(event) {
window.event = event;
}, true);
function clicked() {
// just demonstrating that window.event is set
console.log(window.event.target.innerHTML);
}
document.getElementById('one').addEventListener('click', clicked);
document.getElementById('two').onclick = clicked;
<button id="one">Test 1</button>
<button id="two">Test 2</button>
<button id="three" onclick="clicked()">Test 3</button>
这篇关于Firefox缺少window.event的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!