Javascript - detect if event lister is supported

冷暖自知 提交于 2019-11-29 02:34:56

问题


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.

Thanks if anyone can help!


回答1:


Updated answer:

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.

Example:

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;
    }
}

Live copy

Firefox triggers the callback on all of the modifications above; Chrome on none of them.


Original answer:

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.

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.




回答2:


function isDOMAttrModifiedSupported () {
    var supported = false;
    function handler() {
      supported = true;
    }
    document.addEventListener('DOMAttrModified', handler);
    var attr = 'TEST';
    document.body.setAttribute(attr, 'foo'); // aka $('body').attr(attr, 'foo');
    document.removeEventListener('DOMAttrModified', handler);
    document.body.setAttribute(attr, null);
    return supported;
  }


来源:https://stackoverflow.com/questions/4562354/javascript-detect-if-event-lister-is-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!