bootstrap下拉菜单根据屏幕位置自动下拉? [英] bootstrap drop-down menu auto dropup according to screen position?

查看:215
本文介绍了bootstrap下拉菜单根据屏幕位置自动下拉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道你们中是否有人准备好让我摆脱麻烦.我要寻找的是一个下拉菜单,该下拉菜单会根据其在屏幕上的位置自动添加该下拉菜单类,并且还会在用户滚动或调整窗口大小时自动更改.

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 added according to its position on the screen - and also change automatically when the user scrolls or resizes window.

bootstrap-select插件已经实现了我要查找的内容,但是该插件太沉重",无法使用.

What I am looking for is already implemented in the bootstrap-select plugin, but the plugin is too 'heavy' to use.

推荐答案

有点晚了,但是由于与众不同,因此这是我对引导程序3的解决方案.它适用于页面上的所有下拉菜单,也适用于创建的所有下拉菜单或动态加载.

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.

请注意,我必须使用shown.bs.dropdown事件,因为尺寸仅在那时准备好.

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");
});

如果需要,可以使用 @PeterWone的应用程序高度向导轻松地对其进行改进,目前这对我来说已经足够好了.

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

更新

以下是代表此解决方案的小提琴: http://jsfiddle.net/3s2efe9u/

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

这篇关于bootstrap下拉菜单根据屏幕位置自动下拉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆