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

2020-04-21 02:34发布

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.

2条回答
欢心
2楼-- · 2020-04-21 02:58

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 :)

查看更多
做自己的国王
3楼-- · 2020-04-21 03:24

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;
    }
});
查看更多
登录 后发表回答