Close off-canvas menu on window click

杀马特。学长 韩版系。学妹 提交于 2020-01-04 01:59:06

问题


I made this "slide-out" menu: SASS Slide-out Menu.
It's ok, but I want that when the menu have slid, on window click the menu returns back(remove the class "nav-open").
I tried this on the codepen demo, but it doesn't work:

window.on("click", function(e) {
    if(wrapper.hasClass("nav-open") && e.target != nav && e.target.parent() != nav) {
        wrapper.removeClass("nav-open");
    }
});

回答1:


You're close! I think your codepen example needs the close logic block tweaking to look like this:

  $(window).on("click", function(e) {
    if (
      wrapper.hasClass("nav-open") && 
      !$(e.target).parents(nav).hasClass("side-nav") && 
      !$(e.target).hasClass("toggle")
    ) {
        wrapper.removeClass("nav-open");
      }
  });

Some tips for you:

  1. Use $(window).on not window.on
  2. e.target is a DOM element, so you need to wrap it in jQuery like $(e.target)
  3. You can compare DOM elements, but not jQuery objects, so you can use hasClass instead
  4. I added a check to ignore a click on the toggle itself

Forked codepen with working code: http://codepen.io/anon/pen/mzAru



来源:https://stackoverflow.com/questions/25424783/close-off-canvas-menu-on-window-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!