jquery - Bootstrap 下拉列表位置(上/下)基于文档高度

标签 jquery twitter-bootstrap css drop-down-menu twitter-bootstrap-3

我的页面上有 bootstrap dropmenu 列表。当页面最小化或调整屏幕时,菜单列表将离开屏幕。如果屏幕高度使列表超出屏幕范围,我想检查并向上显示它们。

这是我的html,

 <div  class="btn-group pull-right">                    
 <button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Click<span class="caret"></span></button>
                <ul  class="dropdown-menu pull-right" role="menu">
                    <li>First</li>
                    <li>Second></li>
                    <li>Third</li>
                    <li><Fourth</li>
                    <li>Fifth</li>
                </ul>
            </div>

注意:列表根据高度而不是宽度变化。屏幕的宽度无关紧要,因为我已经在使用“向右拉”,这使我的列表显示在屏幕内。

最佳答案

要使下拉菜单在其切换控件被单击时向上显示,您应该在菜单的容器元素上使用 .dropup 类。要确定何时应用此类,您可以计算展开的下拉列表的底部是否会在窗口下方结束,如果是,则应用 .dropup 类。

一个可能的实现(附加到窗口的 scroll 事件):

function determineDropDirection(){
  $(".dropdown-menu").each( function(){

    // Invisibly expand the dropdown menu so its true height can be calculated
    $(this).css({
      visibility: "hidden",
      display: "block"
    });

    // Necessary to remove class each time so we don't unwantedly use dropup's offset top
    $(this).parent().removeClass("dropup");

    // Determine whether bottom of menu will be below window at current scroll position
    if ($(this).offset().top + $(this).outerHeight() > $(window).innerHeight() + $(window).scrollTop()){
      $(this).parent().addClass("dropup");
    }

    // Return dropdown menu to fully hidden state
    $(this).removeAttr("style");
  });
}

determineDropDirection();

$(window).scroll(determineDropDirection);

这是一个 Bootply展示。尝试缩短演示面板,然后上下滚动面板以查看下拉菜单将如何显示在其切换控件上方/下方,具体取决于可用空间。

希望对您有所帮助!如果您有任何问题,请告诉我。

关于jquery - Bootstrap 下拉列表位置(上/下)基于文档高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32746598/

相关文章:

javascript - 带有可滚动选择列表的 Bootstrap 下拉列表

html - 使用 Bootstrap 3 调整屏幕大小时自动更改按钮文本

jquery - 使 div 宽度随 jQuery 而变化

html - 在 HTML 和 CSS 中只获取 border-bottom

javascript - 仅在表单元素外部触发 jquery 键事件

javascript 不适用于动态添加的选项卡

jquery - 如何在 jQuery 中设置文本区域的宽度?

javascript - 如何在 Navbar-Fixed-Top 中突出显示事件选项卡

javascript - 使表中的整行 float ,同时保持所有其他行就位

javascript - 使用ajax创建新的表行和表单提交