我想知道你们中是否有人准备好我要的东西,以免我遇到麻烦。我正在寻找的是一个下拉菜单,它可以根据其在屏幕上的位置自动添加 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/