2 回答
TA贡献1712条经验 获得超3个赞
尝试一下这个
const load_resize = function() {
var currMenuType = 'desktop';
if (matchMedia('only screen and (max-width: 991px)').matches) {
currMenuType = 'mobile';
}
if (currMenuType !== menuType) {
menuType = currMenuType;
if (currMenuType === 'mobile') {
const mobileMenu = document.getElementById('mainnav')
mobileMenu.setAttribute('id', 'mainnav-mobi')
mobileMenu.hidden = true;
const hasChildMenu = document.getElementById('mainnav-mobi').querySelectorAll('li:has(ul)');
const siteHead = document.getElementById('site-header-inner');
siteHead.parentNode.insertAfter(mobileMenu, siteHead);
hasChildMenu.forEach(li => li.querySelectorAll('ul').forEach(ul => ul.hidden = true));
document.querySelectorAll('.btn-menu')
.forEach(btnmenu => btnmenu.classList.remove('active'));
hasChildMenu.forEach(li => li.querySelectorAll('a').forEach(a => {
const span = document.createElement("span");
span.classList.add("btn-submenu");
a.parentNode.insertAfter(span, a);
}));
} else {
const desktopMenu = document.getElementById('mainnav-mobi')
desktopMenu.setAttribute('id', 'mainnav')
desktopMenu.removeAttribute('style');
desktopMenu.querySelectorAll('.submenu').forEach(sm => sm.removeAttribute('style'));
document.getElementById('header').querySelectorAll('.nav-wrap').forEach(navwrap => {
navwrap.appendChild(desktopMenu); // you need to clone here if more than one
});
document.querySelectorAll('.btn-submenu').forEach(bsm => bsm.remove());
}
}
};
let responsiveMenu = function() {
var menuType = 'desktop';
window.addEventListener('load', load_resize)
window.addEventListener('resize', load_resize)
document.getElementById("container").addEventListener('click', function(e) { // a div container for mobile-button elements
const tgt = e.target;
if (tgt.classList.contains('mobile-button')) {
document.getElementById('mainnav-mobi').classList.toggle("show") // slideToggle(300); needs a transition
tgt.classList.toggle('active');
}
});
document.getElementById("mainnav-mobi").addEventListener('click', function(e) {
const tgt = e.target;
if (tgt.classList.contains('btn-submenu')) {
tgt.classList.toggle('active')
tgt.nextElementSibling.slideToggle(300);
e.stopImmediatePropagation()
}
});
};
添加回答
举报