bootstrap drop-down menu auto dropup according to screen position?

前端 未结 7 723
無奈伤痛
無奈伤痛 2021-02-02 10:33

I was wondering if any of you has what I am asking for ready, to save me from the trouble. What I am looking for is for a dropdown menu to have the dropup class automatically ad

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 11:28

    A bit late, but because is quite different from others, here is my solution for bootstrap 3. It applies globally to all dropdowns on the page, also those created or loaded dynamically.

    Note that I had to use the shown.bs.dropdown event because the dimensions are ready only at that point.

    $(document).on("shown.bs.dropdown", ".dropdown", function () {
        // calculate the required sizes, spaces
        var $ul = $(this).children(".dropdown-menu");
        var $button = $(this).children(".dropdown-toggle");
        var ulOffset = $ul.offset();
        // how much space would be left on the top if the dropdown opened that direction
        var spaceUp = (ulOffset.top - $button.height() - $ul.height()) - $(window).scrollTop();
        // how much space is left at the bottom
        var spaceDown = $(window).scrollTop() + $(window).height() - (ulOffset.top + $ul.height());
        // switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit
        if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown))
          $(this).addClass("dropup");
    }).on("hidden.bs.dropdown", ".dropdown", function() {
        // always reset after close
        $(this).removeClass("dropup");
    });
    

    One could easily improve it with @PeterWone's app height wizardry if needed, currently this was working well enough for me.

    UPDATE

    Here is a fiddle representing this solution: http://jsfiddle.net/3s2efe9u/

提交回复
热议问题