<a onclick=""> display an element, second click close the element. How to do it?

时间:2015-08-23 10:53:36

标签: javascript html css

I have a little problem. When I click on menubutton "x" I trigger an onclick event wich opens/displays an element. So far, so goed... But now I want to click the same menubutton "x" to close that same element. And that is where it goes wrong. I have no idea how to do it.

Here is my html code with the JS.

<a href="#" onclick="submenuAan(); return false;" class="deco-tekst">diensten</a>

*submenuAan (submenu aan) means turn submenu on.

function submenuAan()
{
document.getElementById('menu-vg').style.display = "block";
document.getElementById('menu-vg').style.zIndex = "999";
}

So I thought, when I add an other function behind "return false" for closing, it will work. But it did not.

I hope someone can and will help me. Thanks!

Ps. before someone tells me there already is a simular question like this... I did search, but did not find. If there is, I would like the link to it.

2 个答案:

答案 0 :(得分:1)

您可以使用简单的if语句检查应采取的操作:

<a href="#" onclick="toggleSubmenu();" class="deco-tekst">diensten</a>
function toggleSubmenu(){
  if(document.getElementById('menu-vg').style.display != "block"){
    document.getElementById('menu-vg').style.display = "block";
    document.getElementById('menu-vg').style.zIndex = "999";
  }
  else{
    document.getElementById('menu-vg').style.display = "none";
    document.getElementById('menu-vg').style.zIndex = "auto";
  }
}

答案 1 :(得分:0)

缩小 @ Xufox的 的代码

function toggleSubmenu(){"block"!=document.getElementById("menu-vg").style.display?(document.getElementById("menu-vg").style.display="block",document.getElementById("menu-vg").style.zIndex="999"):(document.getElementById("menu-vg").style.display="none",document.getElementById("menu-vg").style.zIndex="auto")}