Detecting support for a given JavaScript event?

后端 未结 3 504
长发绾君心
长发绾君心 2020-11-29 05:25

I\'m interested in using the JavaScript hashchange event to monitor changes in the URL\'s fragment identifier. I\'m aware of Really Simple History and the jQuery plugins fo

相关标签:
3条回答
  • 2020-11-29 05:42

    Well, the best approach is not going through browser sniffing, Juriy Zaytsev (@kangax) made a really useful method for detecting event support:

    var isEventSupported = (function(){
      var TAGNAMES = {
        'select':'input','change':'input',
        'submit':'form','reset':'form',
        'error':'img','load':'img','abort':'img'
      }
      function isEventSupported(eventName) {
        var el = document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;
        var isSupported = (eventName in el);
        if (!isSupported) {
          el.setAttribute(eventName, 'return;');
          isSupported = typeof el[eventName] == 'function';
        }
        el = null;
        return isSupported;
      }
      return isEventSupported;
    })();
    

    Usage:

    if (isEventSupported('hashchange')) {
      //...
    }
    

    This technique is now used in some libraries like jQuery.

    Read more here:

    • Detecting event support without browser sniffing
    0 讨论(0)
  • 2020-11-29 05:47

    The Mozilla documentation suggests the following:

    if ("onhashchange" in window) {
        alert("The browser supports the hashchange event!");
    }
    

    This works in IE8 and the Chrome 5 beta too (I didn't test Chrome 4.1), and correctly fails in Opera and Safari.

    0 讨论(0)
  • 2020-11-29 06:03

    Here is a modification of the answer provided by CMS, which doesn't contain a function in another, which I think would work:

    function event_exists(eventName){
        if(typeof(eventName)!='string' || eventName.length==0)return false;
        var TAGNAMES = {
            'select':'input','change':'input',
            'submit':'form','reset':'form',
            'error':'img','load':'img','abort':'img'
        }
        var el = document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;
        var isSupported = (eventName in el);
        if (!isSupported) {
            el.setAttribute(eventName,'return;');
            isSupported = (typeof(el[eventName])=='function');
        }
        el = null;
        return isSupported;
    }
    
    0 讨论(0)
提交回复
热议问题