下拉 Javascript 错误:对象不支持属性或方法“匹配”

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

本文关键字:方法 匹配 属性 不支持 Javascript 错误 对象 下拉      更新时间:2023-09-26

我正在使用以下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 中遇到了问题。

看起来您尝试检查单击事件是否由具有类 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');
      }
    }
  }
}

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

if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector;
}

有关跨浏览器解决方案,请查看 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');
根据

http://caniuse.com/#search=matches EDGE对前缀"ms"的部分支持。

相关文章: