首页 > 解决方案 > 此切换脚本适用于除 Internet Explorer 以外的所有浏览器,我该如何解决?

问题描述

基本上我有这个脚本,你可以用一个按钮切换来显示或隐藏一个元素,如果你点击任何不是按钮或目标元素的地方

然后它隐藏了那个目标元素,所以我也喜欢它,所以它适用于除 Internet Explorer 之外的所有浏览器。我目前正在 Internet Explorer 11 上对此进行测试,它一直给我这个错误

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

它引用了这行代码

if (!event.target.matches('#dropbtn')) {

那么我怎样才能让它在 Internet Explorer 上工作,任何代码示例都将受到赞赏,因为我以这种方式学习得最好,而且我在谷歌上找不到任何对我有意义的关于这个问题的东西。

这是我的代码

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

// Prevent event bubble up to window.
document.getElementsByClassName("dropdown-content")[0].addEventListener('click', function(event) {
  event.stopPropagation();
});

// Close the dropdown 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');
      }
    }
  }
}
.dropbtn {
  background-color: lime;
}

.dropdown-content {
  display: none;
}

.show {
  display: block;
}
<meta name="viewport" content="width=device-width">

<button id="dropbtn" onclick="myFunction()">Dropdown</button>

<div class="dropdown-content" style="background:red; height: 300px;"></div>

为未来的读者更新

查看Barmars的回答和我在下面的回答,了解如何让它成功运行。

标签: javascript

解决方案


IE9 没有该matches方法,它调用它msMatchesSelector。使用MDN中的这个 polyfill 自动切换到它。

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

推荐阅读