开发者

Click, Toggle, Jquery

var flip = 0;  
     $("#aabbcc").click(function () {  
         $("#navigation_menu_1").toggle( flip++ % 2 == 0 );  
});

<div id="aabbcc"></div> 
  <div id="navigation_menu_1">
<ul>
  <a href="#"><li>Navigation Item</li></a>
</ul> 

I'm using this small script for a "click menu" What I am trying to accomplish is for the active menu which was called upon by one of the buttons to dispay:none if the mouse leaves the div area which was called upon by one of th开发者_运维知识库e buttons.

So basically I would click the menu button, a div appears, but if i click anywhere out of the div the menu will go back to displaying as none.

This seems simple but I have been at for hours.

Thanks in advance for any suggestions or advice.


Whoa, why the counter?

Why not just:

 $("#aabbcc").click(function () {
     $("#navigation_menu_1").show();
});

Also, you're not handling clicks outside the div at all. So it (should) never disappear. This might be a little slow (needs improvement), but it should work for hiding it again:

$(div).not("#aabbcc").click(function () {
     $("#navigation_menu_1").hide();
});

Again, selecting every div and binding a click event is a bad idea, and I think there might be something along the lines of "Bind to clicks anywhere not on this object," but you get the picture.


One way to do this would be to register a click() on the document. If the event.target.id does not equal some constraint simply hide the navigation.

$(document).click(function(event) {
    var a = $(event.target).andSelf().parents("#navigation_menu_1");
    if (a.length == 0 && $("#navigation_menu_1").is(":visible")) {
        $("#navigation_menu_1").toggle();
    }
});

Code example on jsfiddle.

Also, the flip variable is not needed, you can just call .toggle() directly.


Are you looking to display:none on a click outside of the div or a mouseover / mouseout event? If you are looking to hide when it registers a mouse click outside of the div use this:

jQuery(document).one("click", function() { jQuery("#navigation_menu_1").fadeOut(); });

Example: http://jsfiddle.net/ckaufman/mU89N/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜