简体   繁体   中英

Hide Div onclick outside

On my website I have a div that pops up when the user clicks a form. I am using the onclick event handler for the div to appear. I want the div to hide itself when the user clicks anywhere other than on the div. I cant use onblur...because it doesnt work for divs. Can someone suggest an alternative?

Thank you.

Here is what my code looks like: Javascript:

function hideDiv() {
    if (document.getElementById) { // DOM3 = IE5, NS6 
        document.getElementById('mydiv').style.visibility = 'hidden';
    }
    else {
        if (document.layers) { // Netscape 4 
            document.mydiv.visibility = 'hidden';
        }
        else { // IE 4 
            document.all.mydiv.style.visibility = 'hidden';
        }
    }
}

function showDiv() {
    if (document.getElementById) { // DOM3 = IE5, NS6 
        document.getElementById('mydiv').style.visibility = 'visible';
    }
    else {
        if (document.layers) { // Netscape 4 
            document.mydiv.visibility = 'visible';
        }
        else { // IE 4 
            document.all.mydiv.style.visibility = 'visible';
        }
    }
}

Just found an easy solution using onmouseover / out event handler.

hideDiv() function is called only if variable mouse_out is true.

var mouse_out;
mydiv.onmouseover = function(){ mouse_out = false }; // mouse is over div
mydiv.onmouseout = function(){ mouse_out = true }; // mouse outside
document.onclick = function(){
   if(mouse_out)
      hideDiv(),   // hides mydiv
      document.onclick = null; // disables next clicks on document
};

It works on every browser I tested, also IE 5.
(IE4 and NS4 I don't know)

The way I handled those kind of things in the past is create a transparent layer behind the div (use a BG image that is completely transparent) which has CSS somewhere along the lines of:

div#overlay{
  position: fixed;
  width: 100%;
  height: 100%;
  background-image:url('transparent.gif');
  z-index: 1;
}

This div is of course only "visible" when the Div on top is visible. and then attach an onclick event handler to hide again.

Make sure your "pop-up div" has a z-index of at least 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM