简体   繁体   中英

How to close CSS menu when clicking outside using CSS or JavaScript

I have a dropdown menu on a web page that I created using CSS. It drops down sub menus when hovering over items. It works great on my PC, but on a touchscreen I can't get the menu to close when clicking outside the menu. I can't find a way for the touchscreen to recognize that I am not clicking on the menu anymore.

So basically I need a trigger to be fired to tell the menu to close when I touch the screen anywhere outside the menu.

I would image that I need some sort of Javascript or JQuery trigger. I don't know how this could be done simply with CSS.

I can include the CSS for the menu if you want to see it, but that just creates the menu. I need something that closes the menu and that is not in the CSS.

EDIT:

So far this is the only thing that works, but how can I tell it to ignore the touch if it is on the menu?

$(document).bind('touchstart', function(event) {
      event.preventDefault();                  
      var target = event.target;
      target = $(this);
      alert("touched");
    });

HTML

<div id="menu">
  <ul id="nav">
    <li class="taphover"><a href="#">Tools</a>
      <ul>
        <li><a href="#">Change Password</a></li>
      </ul>
    </li>    

A fairly common way to close something when you click outside of it is to attach a click handler to the body. When that event is fired you check to see if it is not your dropdown and then hide/close it.

Example

$('body').click(function() {
   // Check here is dropdown and close if not
});

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