javascript - 当用户单击链接或页面中的其他任何位置时,JS 隐藏菜单

标签 javascript css menu

我对 JS 一点经验都没有。我搜索了一种编写此菜单的方法,实际上我设法用一点 CSS 实现了它。但是,只有当用户单击关闭按钮时,菜单才会关闭。如果用户单击菜单中的链接或页面中的任何其他位置,菜单将保持打开状态。我想出的代码是这个:

<script>
var theMenu;
var originTop;
 
window.onload = function() {
   //Click to open the submenu
   element = document.getElementById("buttonu101541");
   element.onclick = openMenu;
 
   //Top position
   originTop = document.getElementById("buttonu100976").style.top;
   //Get the Menu element
   theMenu = document.getElementById("buttonu100976");
 
   //Close button
   closeBtn = document.getElementById("buttonu101584");
   closeBtn.onclick = closeMenu;
}
 
function openMenu(){
   theMenu.style.top = 0;
}
 
function closeMenu(){
   theMenu.style.top = originTop;
}
</script>
<style>
   #buttonu100976{
 
      transition-property: top;
      transition-duration: 1s;
      transition-timing-function: ease;
 
      -webkit-transition-property: top;
      -webkit-transition-duration: 1s;
      -webkit-transition-timing-function: ease;
   }

   #buttonu101541{
      cursor: pointer;
      cursor: hand;
   }

   #buttonu101584{
      cursor: pointer;
      cursor: hand;
   }
</style>

老实说,我不知道如何通过这一点。我感谢任何帮助。谢谢。

最佳答案

如果您想通过单击按钮隐藏或显示菜单..您可以试试这个..

当点击“showmenu”按钮时显示菜单;

当点击“hidemenu”按钮时,它会隐藏菜单;

如果这就是您想要的,下面的代码可能会对您有所帮助。

<div id="menu">
<ul>
<li>1</li>
<li>2</li>
</ul>
</div>
<button onclick="document.getElementById('menu').style.display = 'none';">hidemenu</button>
<button onclick="document.getElementById('menu').style.display = 'block';">showmenu</button>

关于javascript - 当用户单击链接或页面中的其他任何位置时,JS 隐藏菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37403758/

相关文章:

javascript - 如何让 Bootstrap 导航栏滑动过渡工作?

html - 如何将 PSD 转换为 HTML,Bootstrap(技巧)

android - 如何或在何处处理由 android actionbar 生成的点击事件

wpf - WPF 应用程序中的菜单/工具栏颜色

javascript - 我可以在 Bootstrap 弹出窗口中使用动态内容吗?

javascript - 从选择中加载选项仅适用于具有类别的第一个项目

css - 使用 :nth-child(n + x) pseudo class 内的变量

jquery - 当部分 jquery hover() 时,CSS 菜单失去焦点

javascript - CanvasContext2D drawImage() 问题 [onload 和 CORS]

javascript - 使用 lodash 过滤另一个数组的元素