Dropdown Javascript error: object doesn't support property or method 'matches'

Dropdown Javascript error: object doesn't support property or method 'matches'

我正在使用以下 JavaScript 下拉菜单,它在除新的 Windows Edge 之外的所有浏览器中都能完美运行。

它显示这个错误:

SCRIPT438: Object doesn't support property or method 'matches'

脚本:

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

脚本来自:http://www.w3schools.com/howto/howto_js_dropdown.asp 我认为它与所有平台兼容。现在我已经实现了它,并且 运行 遇到了 Edge 中的问题。

根据 http://caniuse.com/#search=matches EDGE 部分支持前缀为 'ms'。

您似乎在尝试检查点击事件是否由具有 class dropbtn 的对象触发。

如果您使用 jQuery,您可以这样做:

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!$(event.target).hasClass('dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

如果您不使用 jQuery,您可以获取 class名称,然后检查 dropbtn 是否是其中之一。

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  var classes = event.target.className.split(' ');
  var found = false; var i = 0;
  while (i < classes.length && !found) {
      if (classes[i]=='dropbtn') found = true;
      else ++i;
  }
  if (!found) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

有关跨浏览器的解决方案,请查看 http://youmightnotneedjquery.com/#matches_selector

var matches = function(el, selector) {
  return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
};

matches(el, '.my-class');

前面提到过IE11对它有部分支持。 试试这个

if (!Element.prototype.matches) {

    Element.prototype.matches = Element.prototype.msMatchesSelector;

}