处理其他元素未处理的 JavaScript 事件
我正在编写一个脚本,我想仅处理鼠标事件,如果这些事件之前没有被任何其他元素处理过的话。
我可以将事件侦听器附加到文档对象,但它将接收所有事件,无论它们是否已经被处理过。
我无法控制 HTML 页面中的元素,因此在处理事件时我无法手动
stopPropagation()
。
有什么想法吗?
来自本文 这里 。
似乎目前还无法做到这一点。
Which event handlers are registered?
One problem of the current implementation of W3C’s event registration model is that you can’t find out if any event handlers are already registered to an element. In the traditional model you could do:
alert(element.onclick)
and you see the function that’s registered to it, or undefined if nothing is registered. Only in its very recent DOM Level 3 Events W3C adds an
eventListenerList
to store a list of event handlers that are currently registered on an element. This functionality is not yet supported by any browser , it’s too new. However, the problem has been addressed.
Fortunately
removeEventListener()
doesn’t give any errors if the event listener you want to remove has not been added to the element, so when in doubt you can always use removeEventListener().
因此,您可以在特定情况下完成您想要的事情。具体来说,如果
- 您可以在原始 JavaScript 之前加载您自己的自定义 JavaScript
- 您知道您正在监听哪些元素以让其他元素引发事件
实际上,您所做的就是将目标元素上的原始 addEventListener 方法替换为自定义方法,该方法拦截调用,进行一些特殊处理,然后让它继续正常执行。此“特殊处理”是一个新函数,它包装原始回调,并用某种状态标记事件参数,以便让您知道其他人已经处理了该事件。这是一个概念证明(使用 jsFiddle )
目标 HTML:
<div id='asdf'>asdf</div>
JavaScript:
var target = document.getElementById('asdf');
var original = target.addEventListener;
var updated = function(){
// Grab the original callback, so we can use it in our wrapper
var originalFunc = arguments[1];
// Create new function for the callback, that lets us set a state letting us know it has been handled by someone
// Finish the callback by executing the original callback
var newFunc = function(e){
console.log('haha, intercepted you');
e.intercepted = true;
originalFunc.call(this, e);
};
// Set the new function in place in the original arguments 'array'
arguments[1] = newFunc;
// Perform the standard addEventListener logic with our new wrapper function
original.apply(this, arguments);
};
// Set the addEventListener on our target to our modified version
target.addEventListener = updated;
// Standard event handling
target.addEventListener('click', function(e){
console.log('original click');
console.log('intercepted?', e.intercepted);
})