javascript - 此切换脚本适用于除 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的回答和我在下面的回答,了解如何让它成功运行。
解决方案
IE9 没有该matches
方法,它调用它msMatchesSelector
。使用MDN中的这个 polyfill 自动切换到它。
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
推荐阅读
- android - Json数据没有加载到片段中?
- javascript - 无法从 AJAX 调用向 Web 服务发送值
- python - Python中生成器解包的奇怪行为
- python - 在熊猫中循环合并多个系列
- delphi - 如何动态分配 Windows 消息处理程序?
- c# - c#在listView中搜索项目时延迟加载listView中的项目
- javascript - 如何在函数 worldClockZone 中计算 4 小时 30 分钟的偏移量
- javascript - What's this weird white-space underneath the HTML tag?
- java - 如何使用 spring boot 2 以编程方式获取所有执行器端点?
- javascript - 新窗口加载永远不会在 javascript 中触发