简体   繁体   中英

Show element on click, Hide when click on a different div

The title says it all. I got no problems showing an element when clicked.

But I wanted to hide it whenever I click somewhere else. A good Example of it is the 'StackExchange' label in the header of this site. When I click on it, it will show additional options. But When I click elsewhere, It will hide.

window.onclick = function() { alert('it was so simple, wasn\\'t it?'); };

You can add click event when you clicking something,and judge whether it belongs to html:

function addListener(element, e, fn) {  //add event function,browser compatible
    if (element.addEventListener) {
        element.addEventListener(e, fn, false);
    } else {
        element.attachEvent("on" + e, fn);
    }
}
addListener(document, "click",
function(evt) {
    var evt = window.event ? window.event: evt,
    target = evt.srcElement || evt.target;
    if (target.id == "showDiv") {  //the div you want to show 
        document.getElementById("myDiv").style.display = "";
        return;
    } 
    else {
        //judge target belongs to html or not,You may change condition here
        while (target.nodeName.toLowerCase() != "div" && target.nodeName.toLowerCase() != "html") {  
            target = target.parentNode;
        }
        if (target.nodeName.toLowerCase() == "html") {
            document.getElementById("myDiv").style.display = "none";
        }

    }
})

Michal Leszczyk is right, use window handler to hide div

also use event.stopPropagation() when you show div on click. To prevent hiding it at the same time

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