我试图在移动设备上折叠导航栏,但导航栏只有在我手动调整选项卡大小时才会折叠。所以它可能与启动时不检查屏幕大小有关
网站。
function openNav() {
document.getElementById("mySidebar").style.width = "190px";
document.getElementById("main").style.marginLeft = "190px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}
var x = window.matchMedia("(max-width: 600px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
function myFunction(x) {
if (x.matches) { // If media query matches
closeNav()
}
}
最佳答案
你的问题是 addEventListener()
.您没有在监听 window.matchMedia()
的状态.如果您使用它应该可以工作:
var x = window.matchMedia("(max-width: 600px)")
x.addEventListener("change", () => {
myFunction(x);
});
关于javascript - 为什么我的导航栏在移动时不会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64838970/