7

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

它显示此错误:

SCRIPT438:对象不支持属性或方法“匹配”

脚本:

/* 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 中遇到了问题。

4

4 回答 4

9

看起来您尝试检查单击事件是否由具有类 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,你可以获取 className,然后检查 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');
      }
    }
  }
}
于 2016-04-26T10:17:14.290 回答
5

正如之前提到的,IE11 对它有部分支持。试试这个

if (!Element.prototype.matches) {

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

}
于 2018-08-16T12:57:56.500 回答
3

对于跨浏览器解决方案,请查看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');
于 2016-11-23T17:19:04.913 回答
2

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

于 2016-04-26T09:36:57.217 回答