Keep-bootstrap-3-dropdown-open-when-clicked

2020-04-21 03:14发布

问题:

I need help achieving the same navigation as below link.

It has my code along with clients requirement. And I'm using Bootstrap 3

Bootstrap Dropdowns - dropdown.js

jsfiddle Link

Please help.

回答1:

Updated fiddle

You need to make just one change:

Instead of listening to hide.bs.dropdown event for only .dropdown.active apply the event handler to .dropdown.

Basically, change:

$(".dropdown.active").on("hide.bs.dropdown",function(e) {

to:

$(".dropdown").on("hide.bs.dropdown",function(e) {


EDIT: In order to override the default dropdown behavior, you'll need to ignore the active state since more than one li element can remain expanded and you'll need to toggle visibility yourself.

Here's the updated demo

Code:

$(function(){

    //  Handle show/hide toggle yourself
    $(".dropdown").on("click",function(e) {
        if($(e.currentTarget).hasClass("open"))
            $(e.currentTarget).toggleClass("open",false);
        else 
            $(e.currentTarget).toggleClass("open",true);
        e.preventDefault(); 
        return false;
    });

    //  suppressing default bahavior
    $(".dropdown").on("hide.bs.dropdown", doNothing);            
    $(".dropdown").on("show.bs.dropdown", doNothing);

    function doNothing(e) {
        e.preventDefault(); 
        return false;
    }
});


回答2:

Not sure if its the right way but i did

$(function(){
  $('.nav').find('li.dropdown.active').addClass('open');
  $(".dropdown").on("hide.bs.dropdown",function(e) {
        e.preventDefault(); 
        return false;
   });
  $('.navbar-main li').on('click', function (){
    var me = $(this);
    $('.navbar-main li').removeClass('open');
    $(this).addClass('open');
  });
});

and its working fine :)