jquery - 允许固定垂直菜单在达到一定长度后滚动

标签 jquery menu

我有一个页内导航菜单,当您通过我从其他地方挪用的以下代码向下滚动时,该菜单会切换到固定位置:

    $(document).ready(function () {
          var top = $('#toc2').offset().top - parseFloat($('#toc2').css('marginTop').replace(/auto/, 0));

$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();

// whether that's below the form
if (y >= top) {
  // if so, add the fixed class
  $('#toc2').addClass('fixed');

} 

else {
  // otherwise remove it
  $('#toc2').removeClass('fixed');
}
 });
});

CSS 样式:

#toc2Wrapper { 
 left: 960px;
 position: absolute;
 width: 200px;
font-size:11px;

}

#toc2 {
 position: absolute;
 top: 0;
 background: #FFF;
 padding:3px;
 width: 200px;
 border: 1px solid #E0E0E0;
}

#toc2.fixed {
 position: fixed;
 top: 0;
 }

我的问题是,如果在菜单中切换多个项目,则根据页面内容的性质,页内导航可能会变得相当大。这意味着菜单的长度可以超出窗口底部,并且由于固定位置脚本而变得无法访问(除非其他部分再次折叠)。

我希望能够让菜单在其内部滚动,或者如果底部超出窗口顶部,则允许其从窗口顶部变得不固定,而不是依赖于一次一节的 Accordion 菜单窗口底部。

Android 的网站上有一个很好的例子来说明我想要实现的目标。在相对较短的窗口中展开“应用程序组件”,菜单中会出现一个滚动条:

https://developer.android.com/guide/components/index.html

如何修改现有脚本以允许类似的操作?

最佳答案

在添加固定 div 类之前,您可以在函数中测量并比较窗口高度和 #toc2 高度

$(window).scroll(function (event) {
  // what the y position of the scroll is
  var y = $(this).scrollTop();

  // get your window and toc heights
  var windowheight = $(this).height();
  var tocheight = $('#toc2').height();

  // compare heights
  if(windowheight > tocheight) {
    // only runs add/remove fixed if window height is greater than #toc2
    if (y >= top) {
      // if so, add the fixed class
      $('#toc2').addClass('fixed');
      } 
  else {
    // otherwise remove it
    $('#toc2').removeClass('fixed');
    }
   }
 });

关于jquery - 允许固定垂直菜单在达到一定长度后滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13850104/

相关文章:

javascript - 如何禁用多选下拉列表中的 2 个选项并使该选项变灰

java - 我如何利用二级类(class)来处理我的事件?

jQuery触发点击无限循环

javascript - 在鼠标悬停时展开/折叠 float div 而不会掉到下一行

jquery - Bootstrap 几个字形图标没有显示

css - 停止基于图像的 css 菜单删除

javascript - 单击另一个菜单选项时,如何使所选菜单选项恢复正常?

javascript - 移动导航菜单不起作用(HTML、CSS 和 JQuery)

html - Bootstrap 导航栏菜单 "lagging"?

javascript - 如何在一个类中执行多个 setTimeout jQuery?