2016-05-15 69 views
2

這是我第一次用javvascript做任何事情。目前,我有我的網站驗證碼:試圖讓我的導航欄關閉時,我點擊它?

HTML:

<head> 
<title>My Website</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1" /> 
<link href="navbar.css" rel="stylesheet" type="text/css" /> 
</head> 

<body class="menu"> 
<header> 
<a href="#" class="menu-toggle"><img src="http://i.imgur.com/p2Yxaex.jpg" onmouseover="this.src='http://i.imgur.com/Vrl4tBl.jpg'" onmouseout="this.src='http://i.imgur.com/p2Yxaex.jpg'" /></a> 
<nav class="menu-side"> 
This is a side menu 
</nav> 
</header> 

<br /> 


<center>Content here 
</center> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script> 
<script> 
(function() { 
      var body = $('body'); 
      $('.menu-toggle').bind('click', function() { 
       body.toggleClass('menu-open'); 
       return false; 
       }); 
      })(); 
</script> 
</body> 
</html> 

CSS:

.menu { 
    overflow-x:hidden; 
    position: relative; 
    left: 0px; 
} 

.menu-open { 
    left: 231px; 

} 

.menu-open .menu-side { 
    left: 0; 
} 

.menu-side, 
.menu { 
    -webkit-transition: left 0.2s ease; 
    -moz-transition: left 0.2s ease; 
    transition: left 0.2s ease; 

} 

.menu-side { 
    background-color:#333; 
    border-right:1px solid #000; 
    color:#fff; 
    position:fixed; 
    top: 0; 
    left: -231px; 
    width: 210px; 
    height: 100%; 
    padding: 10px; 


} 

我能做些什麼,這樣我就不需要再點擊菜單圖標,但可以簡單地點擊關閉導航欄關閉它?

謝謝!

+0

您正在尋找這樣的事情[查看外部單擊(http://stackoverflow.com/questions/152975/how-to-detect-a-click -outside-an-element) – natejd04

+0

這些似乎都沒有工作。如果你認爲他們應該,我會放哪個以及如何編輯它? – mutfak

回答

1

你是說在導航欄外點擊關閉它嗎?

此代碼對我的作品,

<a href="#" class="menu-toggle">Toggle menu</a> 
<div id="example_menu" style="display:none"> 
    <a href="#">Test</a> 
    <a href="#">Test</a> 
    <a href="#">Test</a> 
</div> 

<script> 
    $(document).ready(function() { 
     $('.menu-toggle').hover(function() { 
      $('#example_menu').show(); 
     }); 

     // when clicked outside 
     $(this).click(function (e) { 
      var el = $('#example_menu'); 

      if (!el.is(e.target) && el.has(e.target).length === 0) { 
       el.hide(); 
      } 
     }); 
    }); 
</script> 
+0

當我點擊導航欄時,它會淡化「測試」鏈接,但它不會關閉導航欄。 – mutfak