问题描述
是否可以检测某些浏览器是否支持某些事件?我可以检测浏览器是否支持document.addEventListener
,但我需要知道它是否支持事件DOMAttrModified
.Firefox 和 Opera 支持它,但 Chrome 和其他人不支持.
Is it possible to detect if certain events are supported in certain browsers?
I can detect if the browser supports document.addEventListener
, but I need to know if it supports the event DOMAttrModified
. Firefox and Opera support it, but Chrome and others do not.
推荐答案
更新答案:
是的,您可以对此进行特征检测.创建一个元素,监听事件,并更改元素的属性.在我的测试中,您甚至不必将元素添加到 DOM 树中,这使它成为一个很好的、包含的特征检测.
Yes, you can feature-detect this. Create an element, listen for the event, and change an attribute on the element. In my tests, you don't even have to add the element to the DOM tree, making this a nice, contained feature detection.
例子:
function isDOMAttrModifiedSupported() {
var p, flag;
flag = false;
p = document.createElement('p');
if (p.addEventListener) {
p.addEventListener('DOMAttrModified', callback, false);
}
else if (p.attachEvent) {
p.attachEvent('onDOMAttrModified', callback);
}
else {
// Assume not
return false;
}
p.setAttribute('id', 'target');
return flag;
function callback() {
flag = true;
}
}
实时复制
Firefox 触发上述所有修改的回调;Chrome 都没有.
Firefox triggers the callback on all of the modifications above; Chrome on none of them.
原答案:
您可以检测是否支持一些事件,如这个方便页.我不知道您是否可以专门针对该代码进行测试,但如果可以,该代码可能会帮助您入门.
You can feature-detect whether some events are supported, as shown on this handy page. I don't know if you can test specifically for that one, but if you can, that code may well get you started.
更新:我将 Kangax 的代码转储到 JSBin 并试了一下,没有'看起来嗅探技术不适用于该事件(除非我的名称拼写错误或其他东西;Firefox 显示假").但是我上面的技术可以.
Update: I dumped Kangax's code into JSBin and tried it, doesn't look like that sniffing technique works for that event (unless I have the name spelled incorrectly or something; Firefox is showing "false"). But my technique above does.
这篇关于检测是否支持事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!