检测是否支持事件监听器

Detect if event listener is supported(检测是否支持事件监听器)
本文介绍了检测是否支持事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

是否可以检测某些浏览器是否支持某些事件?我可以检测浏览器是否支持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.

这篇关于检测是否支持事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)