Bootstrap 3 – 带侧边栏的Scrollspy

我正在使用Bootstrap 3.我想重新创建与Bootstrap站点上的文档中的侧栏相同的function。

下面是我的代码,它也在这里: http : //bootply.com/82119

两个问题。

  1. 当您向下滚动每个部分的页面时,侧边栏项目不会突出显示。
  2. 当您单击侧栏项时,它会跳转到相关锚点,但一半的内容不可见。 更改data-offset值似乎无效。

我究竟做错了什么?

 

Content 1

At Bootply we attempt to build simple Bootstrap templates that utilize...

Content 2

Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto...

Content 3

Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto...

Content 4

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium...

Content 5

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium...

毕竟你的问题似乎并不重复。 您可以尝试这样的事情: http : //bootply.com/82265

当您单击子窗口中的链接时,内容将隐藏在导航栏后面。 我将您的内容项目包装在额外的div中。 通过这样做,我可以添加一个填充顶部。 填充使h2可见:

 var clicked = false; $('#mynav li a').click( function(){ $('#mycontent > div > h2').css('padding-top',0); $($( this ).attr('href') + ' > h2').css('padding-top','50px'); clicked = true; } ); $('body').on('activate.bs.scrollspy', function () { if(!clicked)$('#mycontent > div > h2').css('padding-top',0); clicked = false; }) 

我发现的问题是一种撤消填充顶部的方法。 我无法使用滚动事件,因为在添加填充后,词缀会触发滚动事件。 撤消’activate.bs.scrollspy’似乎有效。

在bootply我添加了rolllspy $('body').scrollspy({ target: '#sidebar', offset:80 }); 你也可以使用 。 我不确定rolllspy偏移的正确值是什么。 70似乎有点工作。

请注意,我也是最后一个内容项的最小高度,否则您无法滚动最后两个项目。

我认为以上将是一种更为某种概念的certificate然后是一个真正的答案。

注意 Bootstrap的文档会遇到同样的问题。 他们通过在默认情况下在主题之间添加额外的空格来修复此问题,请参阅:

在此处输入图像描述

将在docs.css中添加额外的空白区域:

 h1[id] { margin-top: -45px; padding-top: 80px; } 

另见: https : //github.com/twbs/bootstrap/issues/10670

我遇到了同样的问题,最后通过捕获导航链接上的点击,阻止浏览器处理点击,并在针对页面布局调整的位置手动滚动到目标元素来解决它。 这是代码:

  // figure out a nice offset from the top of the page var scrollTopOffset = $('#main-nav-banner').outerHeight() + 50; // catch clicks on sidebar navigation links and handle them $('.bs-sidebar li a').on('click', function(evt){ // stop the default browser behaviour for the click // on the sidebar navigation link evt.preventDefault(); // get a handle on the target element of the clicked link var $target = $($(this).attr('href')); // manually scroll the window vertically to the correct // offset to nicely display the target element at the top $(window).scrollTop($target.offset().top-(scrollTopOffset)); }); 

scrollTopOffset变量确定项目滚动顶部的接近程度 – 您可能需要根据页面布局调整值的计算。 在上面的例子中,我在页面顶部使用了主导航横幅的高度,并添加了50个像素,因为它“看起来不错”。

除了添加上面的额外代码段之外,无需修改HTML或更改初始化scrollspyfunction的方式。

对我来说,它在Bootstrap v3.0.0下非常巧妙地工作 – 我希望这对其他人也有用!