2016-04-26 55 views
5

我使用以下JavaScript下拉菜單,它適用於除新Windows Edge之外的所有瀏覽器。Dropdown Javascript錯誤:對象不支持屬性或方法「匹配」

它顯示這個錯誤:

SCRIPT438: Object doesn't support property or method 'matches'

腳本:http://www.w3schools.com/howto/howto_js_dropdown.asp我認爲將與所有平臺兼容:

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

從拿到劇本。現在我已經實現了它,並在Edge中遇到了問題。

回答

7

它看起來像你試圖檢查點擊事件是否由類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'); 
     } 
    } 
    } 
} 
+0

謝謝你這麼多@Marc孔特這是一個很大的幫助:-) – Jones

+0

這固定它對於我來說,非常感謝馬克 – Evolve

1

對於一個跨瀏覽器的解決方案,看看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'); 
相關問題