我使用以下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中遇到了问题。
答案 0 :(得分: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');
}
}
}
}
答案 1 :(得分:4)
正如IE11之前部分提到的那样。 试试这个
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
答案 2 :(得分: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');
答案 3 :(得分:2)
根据http://caniuse.com/#search=matches,EDGE部分支持前缀&#39; ms&#39;