Open bootstrap dropdown-toggle to the left

2019-07-25 10:20发布

问题:

My dropdown consists of a button and a ul element. When the button is clicked the ul appears below the button and I would like to change this to appear to the left. I have tried a few things, such as using class="dropdown-submenu pull-left" on the li elements or using data-placement on the button but had no luck.

    <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" title="Grid">
        <span id="glyph" class="glyphicon glyphicon-list-alt" aria-hidden="true"></span>
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a style="cursor: pointer;" data-class="list-alt" onclick="changeGlyph(this)">Grid</a></li>
        <li><a style="cursor: pointer;" data-class="globe" onclick="changeGlyph(this)">Map</a></li>
        <li><a style="cursor: pointer;" data-class="tasks" onclick="changeGlyph(this)">Summary</a></li>
    </ul>
</div>

https://jsfiddle.net/g7pe3e06/1/

回答1:

One solution is to add your custom script, and a little styles.

Put the .dropdown-menu to the top of it's parent(.dropdown is the parent):

.dropdown-menu{
  top: 0;
}

And add some script on Bootstraps show.bs.dropdown dropdown event:

$('.dropdown').on('show.bs.dropdown', function(){

    //get the value (.dropdown-menu's width) and make it negative
    var length = parseInt($('.dropdown-menu').css('width'), 10) * -1; 

    $('.dropdown-menu').css('left', length);
})

Here's the fiddle