如何在点击页面上的任何位置关闭我的下拉菜单

时间:2018-02-03 17:51:12

标签: javascript

当我点击切换按钮时,我可以关闭我的下拉菜单,但是当单击菜单中的任何其他位置时无法关闭它。谁能指出我正确的查询方向。菜单的HTML是

      <nav class="navbar-default navbar-static-side" role="navigation"   
        style="margin-top: 20px" >

        <div class="sidebar-collapse">
            <!-- side-menu -->
            <ul class="nav" id="side-menu" >
             <li>something</li>
            </ul>
         </div>

菜单的js是:

(function ($, window, document, undefined) {

var pluginName = "side-Menu",
    defaults = {
        toggle: true
    };

function Plugin(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}

Plugin.prototype = {
    init: function () {

        var $this = $(this.element),
            $toggle = this.settings.toggle;

        $this.find('li.active').has('ul').children('ul').addClass('collapse in');
        $this.find('li').not('.active').has('ul').children('ul').addClass('collapse');

        $this.find('li').has('ul').children('a').on('click', function (e) {
            e.preventDefault();

            $(this).parent('li').toggleClass('active').children('ul').collapse('toggle');

            if ($toggle) {
                $(this).parent('li').siblings().removeClass('active').children('ul.in').collapse('hide');
            }
        });
    }
};

$.fn[ pluginName ] = function (options) {
    return this.each(function () {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
    });
};

})(jQuery, window, document);

1 个答案:

答案 0 :(得分:1)

实现此目标的最简单方法是在addEventListener对象上创建document并检查目标是否是您的下拉菜单。

在jQuery中:

$(document).click((e) => { 
  if (!$(e.target).closest('#side-menu').length) {
   // close dropdown menu if is visible
  $('#side-menu').removeClass('active').children('ul').collapse('hide');
  }
});

https://jsfiddle.net/etdsu7t9/