香草 JS 模态问题

Vanilla JS modal issue

这对我来说似乎是一个简单的想法,很明显我在这里遗漏了一些东西,如果有任何关于错误的建议,我们将不胜感激。我创建了一个简单的模态框,它会在单击按钮时弹出。我假设通过在 JS 函数中使用 If/else 语句,我可以选择设置按钮 ti 显示或消失。我知道解决这个问题的方法,但我很好奇为什么这个解决方案不起作用

function openNav() {
    let open = document.querySelector('#open');
    open.addEventListener('click', () => {
        let nav = document.querySelector('nav');
        nav.style.display = 'block';
        if (nav.style.display === 'block') {
            open.style.display = 'none';
        } else {
            open.style.display == 'block';
        }
    })
}
openNav();

function closeNav() {
    let close = document.querySelector('#close');
    close.addEventListener('click', () => {
        let nav = document.querySelector('nav');
        nav.style.display = 'none';
        if (nav.style.display === 'block') {
            close.style.display = 'block';
        } else {
            close.style.display = 'none';
        }
    })
}
closeNav();

该按钮确实可以在模式关闭后打开模式,但“打开”按钮不会重新出现。

您没有将打开按钮设置回在导航关闭时阻止。试试这个代码:

function openNav() {
    let open = document.querySelector('#open');
    open.addEventListener('click', () => {
        let nav = document.querySelector('nav');
        nav.style.display = 'block';
        open.style.display = 'none';
        close.style.display = 'block';
        /*
        if (nav.style.display === 'block') {
            open.style.display = 'none';
        } else {
            open.style.display == 'block';
        }
        */
    })
}
openNav();

function closeNav() {
    let close = document.querySelector('#close');
    close.addEventListener('click', () => {
        let nav = document.querySelector('nav');
        nav.style.display = 'none';
        open.style.display = 'block';
        close.style.display = 'none';
        /*
        if (nav.style.display === 'block') {
            close.style.display = 'block';
        } else {
            close.style.display = 'none';
        }
        */
    })
}
closeNav();

我认为您假设 if 块正在监视 display。然而,它并没有,它只在函数调用中检查一次。

您也可以将其更改为切换,因为您只应使用此功能一次来添加事件侦听器

function toggleNav() {
    const open = document.querySelector('#open');
    const close = document.querySelector('#close');
    const nav = document.querySelector('nav');
    
    open.addEventListener('click', () => {
        nav.style.display = 'block';
        close.style.display = 'block';
        open.style.display = 'none';
    })
    
    close.addEventListener('click', () => {
        nav.style.display = 'none';
        close.style.display = 'none';
        open.style.display = 'block';
    })
}
toggleNav();
#close, nav {
  display:none;
}
<button id="open">Open nav</button>
<button id="close">Close nav</button>
<nav>Nav</nav>

还有一些错误:

if (nav.style.display === 'block') {
   open.style.display = 'none';
} else {
   open.style.display == 'block'; // This is a comparison
}