开发者

Change class onclick anyplace on document to close a menu?

I use this code which opens and closes a menu. How can I have it close when someone clicks anyplace on the screen?

function showElement(layer){
var myLayer = document.getElementById(layer);
if(myLayer.style.display=="none"){
    myLayer.style.display="block";
    myLayer.backgroundPosition="top";
} else { 
    myLayer.style.display="none";
}
}

The HTML

<div style="float:left;">
<a href="#" class="button" onclick="javascript:showElement('v-menu')">
<span>Monitoring</span></a>
<ul id="v-menu" class="v-menu" style="display:none;" >
<li><a href="#" onclick="javascript:showElement('v-menu')">Start</a></li>
<li>&开发者_StackOverflowlt;a href="#">Stop</a></li>
</div>


You will need to do two things to achieve this:

Bind a click event for the whole document, and hide the menu if it is shown.

document.addEventListener("click", function(event) {
    var menu = document.getElementById('v-menu');
    if (event.target !== menu && menu.style.display == 'block')
        menu.style.display = "none";
});

Stop the click event propagation when the menu is clicked, so the event does not bubble up to the document.

<a href="javascript:void(0)" class="button" 
    onclick="showElement('v-menu'); event.stopPropagation()">

See this in action: http://jsfiddle.net/william/Pfv8N/.


You can attach an event on document.body and in the handler you can write your code to hide the menu like this

    document.body.addEventListener("click", function(){

         //conditions to check if click is not on ur menu
         showElement();

     }, false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜