香草JS模态问题

时间:2020-10-09 18:43:59

标签: javascript html css modal-dialog

在我看来,这似乎是一个简单的主意,很明显,我在这里遗漏了一些东西,关于出现问题的任何建议将不胜感激。我创建了一个简单的模式,单击该按钮时将弹出该模式。我假设通过在JS函数中使用If / else语句,我可以选择设置按钮ti show或消失。我知道可以解决此问题,但我很好奇为什么此解决方案不起作用

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();

按钮关闭后确实可以打开模态,但“打开”按钮不会出现。

2 个答案:

答案 0 :(得分:0)

关闭导航栏时,您没有将打开按钮设置回阻止状态。请尝试以下代码:

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。但是,它不会,它只会在函数调用中检查一次。

答案 1 :(得分:0)

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

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
}