通过 jQuery 更改 'affix' 单击按钮时的顶部偏移

Change 'affix' offset-top on click a button by jQuery

我想通过单击 jQuery 按钮更改 'affix' 偏移顶部。

          $('#nav2').affix({
                offset: {
                  top: $("#nav1").height()+58
                }
          });

运行良好,但在加载包含代码的页面后我无法更改最高值。

你可以这样做:

$('#nav2')
    .affix({
        top: YOUR-NEW-VALUE
    })
    .affix('checkPosition'); // this will recalculate the position

编辑 回答您的建议,Bootstrap 附加文档声明:

(checkPosition) Recalculates the state of the affix based on the dimensions, position, and scroll position of the relevant elements. The .affix, .affix-top, and .affix-bottom classes are added to or removed from the affixed content according to the new state. This method needs to be called whenever the dimensions of the affixed content or the target element are changed, to ensure correct positioning of the affixed content.

所以不需要把类全部去掉再重新初始化affix。只需使用上面的代码片段即可。

有关 Bootstrap affix 的更多信息,请参见 here

最好的选择是星期四 css:

#nav2 {
    position: fixed;
    top: YOUR-INITIAL-POSITON
}

然后使用 jQuery 仅更改顶部位置:

$('#nav2').css('top', YOUR-NEW-VALUE);

希望对您有所帮助。