关闭导航选项卡单击

时间:2017-01-28 15:37:03

标签: javascript jquery html css nav

您好我有以下代码来创建导航标签,当我点击其中一个列表时它会关闭但是如果我点击它就不会关闭,我是新来的,所以任何帮助都会很棒

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, iniitial-scale=1">
    <title>Home</title>

<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>

<!-- NAVIGATION TAB-->

<nav>

    <a href="#" class="nav-togg"></a>

    <ul>
    <h1 class="navhead1">HOME</h1>
        <li><a href="Home.html">Home</a></li>
        <li><a href="About.html">About</a></li>
        <li><a href="Products.html">Products</a></li>
        <li><a href="Contact.html">Contact</a></li>
    </ul>


</nav>

<script       src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">


(function() {

    var bodyEl = $('body'),
        navTogg = bodyEl.find('.nav-togg');

        navTogg.on('click', function(e){
            bodyEl.toggleClass('active-nav');
            e.preventDefault();

        });



})();

当我点击页面上的任何地方时,我想让它关闭 谢谢

沙克

1 个答案:

答案 0 :(得分:0)

这可以通过检查点击区域来处理:

$(document).ready(function(){
		
    $(document).on('click',function(e){
	if($(e.target).closest('.nav-togg').length)
	    $('body').toggleClass('active-nav');
	else
	    $('body').removeClass('active-nav');
    });
});
nav ul{
  display: none; 
}
.active-nav nav ul{
  display: block; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<nav>

    <a href="#" class="nav-togg">toggle</a>

    <ul>
    <h1 class="navhead1">HOME</h1>
        <li><a href="Home.html">Home</a></li>
        <li><a href="About.html">About</a></li>
        <li><a href="Products.html">Products</a></li>
        <li><a href="Contact.html">Contact</a></li>
    </ul>


</nav>