How to hide div by onclick using javascript?

前端 未结 3 911
星月不相逢
星月不相逢 2021-01-19 14:40

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



        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-19 15:10

    HTML

    show/hide
    

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

提交回复
热议问题