Bootstrap navigation bar can be clicked and mouse hover display drop down menu implementation code

  • 2021-07-01 06:01:28
  • OfStack

When using the Bootstrap navigation bar component, If your navigation bar has a drop-down menu, then the navigation with a drop-down menu will only surface when clicking, and its own href attribute will be invalid, that is, it will lose the hyperlink function, which is not what I want. I hope the link of the navigation bar can open its link normally, but I need the drop-down menu function and start tossing ~

First of all, solve the problem that the navigation bar with drop-down menu can be clicked. The drop-down menu effect is realized by JS. By analyzing bootstrap. js file, it is found that Bootstrap writes the drop-down menu as an JQuery plug-in, and finds a few key words in dropdown code segment:


// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)

After finding a few key codes, I thought of a solution. Just turn off the click. bs. dropdown. data-api events, and the code is as follows:


$(document).ready(function(){
$(document).off('click.bs.dropdown.data-api');
});

The above code test is effective, the navigation bar can click to solve the problem, and the following solution to the mouse hover drop-down menu problem, which is relatively simple, can be realized with the mouse event of JQuery, the code is as follows:


$(document).ready(function(){
dropdownOpen();// Call 
});
/**
*  Expand the submenu with a mouse stroke, so as not to need to click to expand it 
*/
function dropdownOpen() {
var $dropdownLi = $('li.dropdown');
$dropdownLi.mouseover(function() {
$(this).addClass('open');
}).mouseout(function() {
$(this).removeClass('open');
});
}

Related articles: