Jon*_*nes 7 javascript methods jquery multiple-matches drop-down-menu
我正在使用以下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');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
得到了以下脚本:http://www.w3schools.com/howto/howto_js_dropdown.asp,我认为它与所有平台兼容.现在我已经实现了它,并在Edge中遇到了问题.
看起来您尝试检查click事件是否由具有类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');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你不使用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');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如之前提到的,IE11 部分支持它。尝试这个
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
Run Code Online (Sandbox Code Playgroud)