【问题标题】:Sliding sidebar position calculations not correct滑动侧边栏位置计算不正确
【发布时间】:2014-04-10 00:44:05
【问题描述】:

我正在 jQuery 中为我正在开发的网站构建一个关注或粘性侧边栏。

Here's a link to the site with the sidebar.

你可以看到它的行为很奇怪。我正在尝试遵循本指南并在到达底部后添加停止功能:

http://css-tricks.com/scrollfollow-sidebar/

当用户向下滚动时,我希望侧边栏以 32px 的顶部填充保持在顶部,当用户滚动到底部时,我希望侧边栏在顶部以 32px 的底部填充停止页脚。我对变量和它背后的数学感到困惑,在我看来这是有道理的,但也许我需要其他人来看看它。

无论如何,这是 jQuery 代码:

<script>
$(function() {
    var $sidebar   = $("#sidebar"), 
        $window    = $(window),
        $footer    = $("footer"), // use your footer ID here
        foffset    = $footer.offset(),
        offset     = $sidebar.offset(),
        threshold  = foffset.top - $sidebar.height(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > threshold) {
            $sidebar.stop().animate({
                marginTop: threshold
            });
        } else if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $sidebar.height() - offset.top + topPadding
            }, 400);
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            }, 400);
        }
    });
});
</script>

以及侧边栏 ID 的 CSS:

#sidebar { 
  position: fixed !important; 
}

提前致谢。

【问题讨论】:

    标签: jquery sidebar sticky


    【解决方案1】:

    试试这个包括填充你的计算:

    threshold  = foffset.top - $sidebar.outerHeight(),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 2018-12-20
      • 2017-12-16
      • 1970-01-01
      相关资源
      最近更新 更多