下拉菜单JavaScript错误:对象不支持属性或方法'matches'

7

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

它显示以下错误:

SCRIPT438:对象不支持属性或方法“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浏览器中遇到了问题。

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');
      }
    }
  }
}

非常感谢 @Marc Compte,这对我帮助很大 :-) - Jones

5

正如之前提到的,IE11对其有部分支持。 请尝试以下操作:

if (!Element.prototype.matches) {

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

}

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');

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接