Javascript 如何使用javascript通过onclick隐藏div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3177582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:33:34  来源:igfitidea点击:

How to hide div by onclick using javascript?

javascriptonclickhide

提问by Jay

I have used a javascript to show div by onclick but when i click outside div i want to hide the div. How to do it in javascript? i'm using javascript code..

我使用 javascript 通过 onclick 显示 div,但是当我在 div 外单击时,我想隐藏 div。如何在javascript中做到这一点?我正在使用 javascript 代码..

<a href="javascript:;" onClick="toggle('one');">  

function toggle(one)
{
    var o=document.getElementById(one);

    o.style.display=(o.style.display=='none')?'block':'none';
}

回答by gblazex

HTML

HTML

<a href="#" onclick="toggle(event, 'box');">show/hide</a>

Javascript

Javascript

// click on the div
function toggle( e, id ) {
  var el = document.getElementById(id);
  el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';

  // save it for hiding
  toggle.el = el;

  // stop the event right here
  if ( e.stopPropagation )
    e.stopPropagation();
  e.cancelBubble = true;
  return false;
}

// click outside the div
document.onclick = function() {
  if ( toggle.el ) {
    toggle.el.style.display = 'none';
  }
}

回答by D.J

you can use blur() function when you clicked somewhere else

单击其他地方时可以使用 blur() 函数

$("#hidelink").click(function() {
    $("#divtoHide").show();
});

$("#hidelink").blur(function() {
    $("#divtoHide").hide();
});

回答by alecwh

Use jQuery and this will be as easy as:

使用 jQuery,这将非常简单:

$("button.hide").click(function(event){ $("div.hidethis").hide() });

$("button.hide").click(function(event){ $("div.hidethis").hide() });