thewindsword
3/22/2019 - 6:30 AM

HTML EXAM 29

(function() {
  // matches 的 polyfill
  if (!Element.prototype.matches) {
    Element.prototype.matches = 
        Element.prototype.matchesSelector || 
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector || 
        Element.prototype.oMatchesSelector || 
        Element.prototype.webkitMatchesSelector ||
        function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while (--i >= 0 && matches.item(i) !== this) {}
            return i > -1;            
        };
  }
  if (!Element.prototype.closest) {
    // 第一题
    Element.prototype.closest = function (selector) {
      let el = this;
      while (el && el.nodeType === 1) {
        if (el.matches(selector)) {
          return el;
        }
        el = el.parentNode;
      }
      return null;
    }
    // 第一题 END
  }
  if (!Element.prototype.closestAll) {
    // 第二题
    Element.prototype.closestAll = function (selector) {
      let el = this.parentNode;
      let nodeList = null;
      while (el && el.nodeType === 1) {
        if (el.matches(selector)) {
          if (!nodeList) {
            nodeList = [];
          }
          nodeList.push(el);
        }
        el = el.parentNode;
      }
      return nodeList;
    }
    // 第二题 END
  }
})()