我正在使用以下 JavaScript 下拉菜单,它在除新的 Windows Edge 之外的所有浏览器中都能完美运行。
它显示这个错误:
SCRIPT438: Object doesn't support property or method '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 中遇到了问题。
最佳答案
您似乎在尝试检查点击事件是否由具有 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,您可以获取类名,然后检查 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');
}
}
}
}
关于javascript - 下拉 Javascript 错误 : object doesn't support property or method 'matches' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859054/