How to hide div by onclick using javascript?

江枫思渺然 提交于 2019-12-01 21:09:00

问题


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..

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

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

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

回答1:


HTML

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

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';
  }
}



回答2:


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

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

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



回答3:


Use jQuery and this will be as easy as:

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



来源:https://stackoverflow.com/questions/3177582/how-to-hide-div-by-onclick-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!