จะซ่อน div โดย onclick โดยใช้ javascript ได้อย่างไร

ฉันใช้จาวาสคริปต์เพื่อแสดง div โดย onclick แต่เมื่อฉันคลิก div ภายนอก ฉันต้องการซ่อน div จะทำอย่างไรในจาวาสคริปต์? ฉันใช้รหัสจาวาสคริปต์ ..

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

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

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

person Jay    schedule 05.07.2010    source แหล่งที่มา


คำตอบ (3)


HTML

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

จาวาสคริปต์

// 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';
  }
}
person gblazex    schedule 05.07.2010

คุณสามารถใช้ฟังก์ชัน blur() เมื่อคุณคลิกที่อื่น

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

$("#hidelink").blur(function() {
    $("#divtoHide").hide();
});
person D.J    schedule 05.07.2010

ใช้ jQuery และจะง่ายเหมือน:

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

person alecwh    schedule 05.07.2010