Bootstrap4 multi-level menu

      After the Bootstrap4 update, many original functions have been changed. For example, btn-default has disappeared. I don't understand the developer's routine at all. A new problem has arisen in the multi-level menu, that is, when you click an item in the Dropdown menu and call out another menu, the original menu disappears and the new menu does not appear.

      Carefully read the source code and the official document, and found such a content:

      

      It is decided to prevent the menu from disappearing if it is determined that the calling source is in the menu by responding to this event before the menu disappears. Then I checked the source code of the dropdown file in bootstrap4 and found this paragraph:      

const DATA_KEY                 = 'bs.dropdown'
const EVENT_KEY                = `.${DATA_KEY}`

/*...省略*/

const Event = {
  HIDE             : `hide${EVENT_KEY}`,
 /*...省略*/
}

// Event.HIDE 的值即为:hide.bs.dropdown
const hideEvent = $.Event(Event.HIDE, relatedTarget)
$(parent).trigger(hideEvent)
if (hideEvent.isDefaultPrevented()) {
  continue
}

      That is to say, you only need to execute the following sentence in the code:

e.preventDefault();

      The pop-up window can be prevented from disappearing, and the rest is about how to determine whether the source of the click event is the element we want. We can set a data-tag in the HTML code, and then judge it in js. The code is as follows:

HTML code: add data-submenu="true"

<a class="dropdown-toggle" data-submenu="true" href="#" data-toggle="dropdown" aria-haspopup="true"
   aria-expanded="false" data-boundary="window">{{m3Menu.title}}</a>

JS code: The source element can be obtained by the following code

var winEvent = window.event;
if (winEvent) {
    var srcEle = winEvent.srcElement;
    if ($(srcEle).data("submenu")) {
        e.preventDefault();
    }
}

      Then there is a small bug: that is, if there are two menus in a drop-down menu, you can call out the next-level menu. After the first one is called out, click the second one, and the first called out menu will not disappear, which requires more further judgment.

      Complete JS code:

$(".dropright,.dropdown").on("hide.bs.dropdown", function (e) {
    var winEvent = window.event;
    if (winEvent) {
        var srcEle = winEvent.srcElement;
        if ($(srcEle).data("submenu")) {
            e.preventDefault();
        }
    }
});

      It should be noted that the parameter e in jquery is not the same object as window.event.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325483075&siteId=291194637