简体   繁体   English

使用JavaScript显示另一个div时隐藏一个div

[英]Hide one div when showing another with JavaScript

I'm trying to create a with a "popup" submenu on click. 我试图在点击时创建一个带有“弹出”子菜单的。

There's three separate submenus, and I can get them to show with Javascript, except they stack on top of each other. 有三个单独的子菜单,除了它们相互堆叠之外,我可以用Javascript来显示它们。 How can I hide the previously shown div when the next one is clicked? 当单击下一个div时,如何隐藏上一个显示的div?

Can I do this with pure CSS? 我可以使用纯CSS做到这一点吗?

See this pen for more details. 有关更多详细信息,请参见此笔

You need to remember which was opened. 您需要记住哪个已打开。 Try this for your javascript function: 为您的javascript函数尝试一下:

var current = null;
function toggle_visibility(id) {
  var e = document.getElementById(id);
  if (current !== null) {
    current.style.display = 'none';
  }
  if (e == current) {
    return;
  }
  if (e.style.display == 'block') {
    e.style.display = 'none';
  } else {
    e.style.display = 'block';
    current = e;
  }
}

Assign class names to the sub-menus. 将类名称分配给子菜单。 Before opening a new menu, get the sub-menus by class name, loop over them and hide them. 在打开新菜单之前,请按类名称获取子菜单,然后在其上循环并隐藏它们。 Then open the selected one by id. 然后按ID打开所选的ID。

Using jQuery you can do something along this line : 使用jQuery,您可以沿着这条线做一些事情:

    $(".submenu").click(function () {
      var currentSubMenu = $('.menu').find('.submenu.active');

      if (this === currentSubMenu)
        return;

      $(currentSubMenu).removeClass('active').hide();
      $(this).addClass('active').show();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM