单击模态外部时,Javascript模式不会关闭

时间:2017-09-27 08:33:34

标签: javascript modal-dialog

所以我是javascript的新手,我正在尝试为包含我的Nav的网站设置模态。我希望每当用户点击它时,模态就会关闭,这很容易,而且很多教程向我展示了不同的方法,但所有这些方法都是错误或不起作用。这里的参考是我的html:

    <!DOCTYPE html>
<html>
    <head>
        <title>Joe's Cars</title>
        <link rel="stylesheet" type="text/css" href="style.css" >
        <script src="https://use.fontawesome.com/d862ed6876.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Lora|Raleway|Source+Sans+Pro" rel="stylesheet">

    </head>
    <body>
        <header>
            <button id="openNav"><i class="fa fa-bars" aria-hidden="true"></i></button>
        </header>

        <div class="navModal" id="navModal">
            <p>Navigation</p>
            <button  id="closeNav">close</button>
        </div>

        <script src="nav.js"></script>
    </body>
</html>

javascript如下:

    var modal = document.getElementById('navModal');
var openBtn = document.getElementById('openNav');
var closeBtn = document.getElementById('closeNav');

function openNav() {
    modal.style.display = "block";
}

function closeNav() {
    modal.style.display = "none";
}

function outsideClick(e) {
    console.log('outside click called');
    if(e.target == modal){
        console.log('if statement executed');
        modal.style.display = 'none';
    }
}


openBtn.addEventListener('click', openNav);
closeBtn.addEventListener('click', closeNav);
window.addEventListener('click', outsideClick); 

当我在导航栏外部单击时,将调用窗口单击并且控制台将其记录在“外部单击调用”之外,但if语句不会执行。这可能是显而易见的事情,但我之前从未使用过javascript事件处理程序,谷歌搜索提出的东西超出了我能理解的范围。

全部谢谢

1 个答案:

答案 0 :(得分:0)

您不应该if(e.target == modal){而是if(e.target !== modal){

您还应将openNav更改为:

function openNav(e) {
    e.stopPropagation();
    modal.style.display = "block";
}

否则,当您单击打开按钮时,它将打开和关闭您的模态。