使用Event.target和类关闭屏幕外导航

时间:2017-12-19 14:40:13

标签: javascript jquery html css

我需要一些帮助来理解event.target属性。

我创建了一个nav,在点击button时可以滑入和滑出。当nav出现在屏幕上时,它会添加类nav-open。我试图添加一些功能,如果用户单击,但nav 会关闭,所以我尝试定位:

  1. 班级名称
  2. 用户点击
  3. 使用以下代码,但它似乎不起作用:

        $(window).click(function(e) {
            if( nav.hasClass('nav-open') && e.target != nav ) {
                nav.removeClass('nav-open');
            }
    
        });
    

    有人可以帮忙吗?下面的完整片段。

    $(document).ready(function() {
    	
    	var button = $('button');
    	var nav = $('nav');
    	
    	button.click(function() {
    		nav.toggleClass('nav-open');
    	});
    	
    // 	$(window).click(function(e) {
    // 		if( nav.hasClass('nav-open') && e.target != nav ) {
    // 			nav.removeClass('nav-open');
    // 		}
    		
    // 	});
    	
    	
    	
    	
    });
    * {
    	padding: 0;
    	margin: 0;
    }
    
    .container {
    	border: 1px solid;
    	height: 1000px;
    	width: 100%;
    	background-color: #ccc;
    	position: relative;
    	z-index: 1;
    }
    
    button{
    	position: relative;
    	left: 500px;
    	top: 30px;
    }
    
    nav {
    	height: 100vh;
    	width: 300px;
    	left: 0;
    	top: 0;
    	position: absolute;
    	background-color: #444;
    	z-index: 2;
    	transform: translate3d(-300px,0,0);
    	transition: all .4s ease;
    }
    .nav-open {
    	transform: translate3d(0px,0,0);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <nav></nav>
    <div class="container">
    	<button>click me</button>
    </div>

1 个答案:

答案 0 :(得分:2)

您需要event.stopPropagation()才能防止事件冒泡。

&#13;
&#13;
$(document).ready(function() {
	
	var button = $('button');
	var nav = $('nav');
	
	button.click(function() {
		nav.toggleClass('nav-open');
	});
	
  $("body").on("click", ".container", function(e){
    e.preventDefault();
    if($("nav").hasClass("nav-open")){
      $("nav").removeClass("nav-open");
    }
  }).on("click", "nav, button", function(){
    e.stopPropagation();
  })
	
	
	
	
});
&#13;
* {
	padding: 0;
	margin: 0;
}

.container {
	border: 1px solid;
	height: 1000px;
	width: 100%;
	background-color: #ccc;
	position: relative;
	z-index: 1;
}

button{
	position: relative;
	left: 500px;
	top: 30px;
}

nav {
	height: 100vh;
	width: 300px;
	left: 0;
	top: 0;
	position: absolute;
	background-color: #444;
	z-index: 2;
	transform: translate3d(-300px,0,0);
	transition: all .4s ease;
}
.nav-open {
	transform: translate3d(0px,0,0);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav></nav>
<div class="container">
	<button>click me</button>
</div>
&#13;
&#13;
&#13;