单击关闭菜单/ div以关闭

Gol*_*naz 1 javascript jquery

当我点击页面上的任何地方时,我一直试图让我的菜单关闭,除了在菜单中.

我设法实现这一点,当菜单中的链接被点击时,通过给它提供与菜单按钮相同的onclick功能,但我没有成功点击菜单关闭它.

http://codepen.io/anon/pen/LEvdmW

JS

function setVisibility(id) {
  var targetButton;
  switch( id ) {
    case "layer":
      targetButton = "button";
      break;
  }
  if (document.getElementById(targetButton).value == 'Close') {
    document.getElementById(targetButton).innerHTML = 'Open';
    document.getElementById(targetButton).value = 'Open';
    document.getElementById(id).style.display = 'none';
  } else {
    document.getElementById(targetButton).innerHTML = 'Close';
    document.getElementById(targetButton).value = 'Close';
    document.getElementById(id).style.display = 'inline';
  }
}
Run Code Online (Sandbox Code Playgroud)

HTML

<button name="type" id="button" onclick="setVisibility('layer')">Open</button>
<div id="layer"><a onclick="setVisibility('layer')"> Hello</div>
Run Code Online (Sandbox Code Playgroud)

CSS

#layer {
    position: absolute;
    left: 8px;
    top: 50px;
    background-color: #989898;
    width: 280px;
    height: 100px;
    padding: 10px;
    color: black;
    display: none;
}


button {  border:none; background:#989898; color:#fff; padding:10px; outline:none; cursor:pointer;

}
Run Code Online (Sandbox Code Playgroud)

Jit*_*oli 5

它可以通过以下代码实现.

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

工作小提琴:http://jsfiddle.net/LCB5W/153/

更新小提琴:http://jsfiddle.net/LCB5W/154/