jquery - Bootstrap 下拉菜单根据屏幕位置自动下拉?

标签 jquery css twitter-bootstrap twitter-bootstrap-3

我想知道你们中是否有人准备好我要的东西,以免我遇到麻烦。我正在寻找的是一个下拉菜单,它可以根据其在屏幕上的位置自动添加 dropup 类,并在用户滚动或调整窗口大小时自动更改。

我正在寻找的东西已经在 bootstrap-select 插件中实现,但该插件太“重”而无法使用。

最佳答案

有点晚了,但因为与其他人完全不同,这里是我的 bootstrap 3 解决方案。它全局适用于页面上的所有下拉菜单,也适用于动态创建或加载的下拉菜单。

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

$(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's app height 轻松改进它如果需要的话,魔法,目前这对我来说已经足够好了。

更新

这是代表此解决方案的 fiddle :http://jsfiddle.net/3s2efe9u/

关于jquery - Bootstrap 下拉菜单根据屏幕位置自动下拉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21232685/

相关文章:

javascript - 关闭时如何在对话框中杀死所有生命?

javascript - 如何在单击按钮时同时运行表单操作和单击事件

html - 如何在保持交叉兼容性的同时使用 CSS/CSS3 应用此效果

javascript - 为什么在编译包含指令的 html 文本(来自 db)时出现无限摘要错误

javascript - Rails 应用程序 : require bootstrap vs require bootstrap-sprockets

css - 使用 CSS/Bootstrap 的页脚问题

javascript - 根据输入中的值重新获取 FullCalendar 事件

javascript - jQuery 回调 - 添加新元素时似乎切换元素 "on and off"

jquery - 当浏览器窗口失去焦点时,Flexslider 停止工作

javascript - 我的 html css 程序中的可见性问题