滚动然后固定的侧边栏内容在向上滚动时消失

时间:2015-07-01 03:28:59

标签: javascript jquery html css twitter-bootstrap-3

我有一个右侧栏滚动到内容的末尾然后修复,但是在偶尔向上滚动内容消失。有没有办法在向上滚动时将内容“修复”到侧栏的顶部?我正在使用Bootstrap 3并在Bootply(http://www.bootply.com/mbjviJQBxv)中重新创建了这个,这里是我改编为Ryan Maxwell的脚本:

$(function() {

var $window = $(window);
var lastScrollTop = $window.scrollTop();
var wasScrollingDown = true;

var $sidebar = $(".rightSideBar");
if ($sidebar.length > 0) {

    var initialSidebarTop = $sidebar.position().top;

    $window.scroll(function(event) {

        var windowHeight = $window.height();
        var sidebarHeight = $sidebar.outerHeight();

        var scrollTop = $window.scrollTop();
        var scrollBottom = scrollTop + windowHeight;

        var sidebarTop = $sidebar.position().top;
        var sidebarBottom = sidebarTop + sidebarHeight;

        var heightDelta = Math.abs(windowHeight - sidebarHeight);
        var scrollDelta = lastScrollTop - scrollTop;

        var isScrollingDown = (scrollTop > lastScrollTop);
        var isWindowLarger = (windowHeight > sidebarHeight);

        if ((isWindowLarger && scrollTop > initialSidebarTop) || (!isWindowLarger && scrollTop > initialSidebarTop + heightDelta)) {
            $sidebar.addClass('fixed');
        } else if (!isScrollingDown && scrollTop <= initialSidebarTop) {
            $sidebar.removeClass('fixed');
        }

        var dragBottomDown = (sidebarBottom <= scrollBottom && isScrollingDown);
        var dragTopUp = (sidebarTop >= scrollTop && !isScrollingDown);

        if (dragBottomDown) {
            if (isWindowLarger) {
                $sidebar.css('top', 0);
            } else {
                $sidebar.css('top', -heightDelta);
            }
        } else if (dragTopUp) {
            $sidebar.css('top', 0);
        } else if ($sidebar.hasClass('fixed')) {
            var currentTop = parseInt($sidebar.css('top'), 10);

            var minTop = -heightDelta;
            var scrolledTop = currentTop + scrollDelta;

            var isPageAtBottom = (scrollTop + windowHeight >= $(document).height());
            var newTop = (isPageAtBottom) ? minTop : scrolledTop;

            $sidebar.css('top', newTop);
        }

        lastScrollTop = scrollTop;
        wasScrollingDown = isScrollingDown;
    });
}

我搜索了Stack Overflow的解决方案,但找不到一个,我是脚本新手并感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

你可以用CSS

来做到这一点
.rightSideBar{
     position: fixed;
     top: 0;
     right: 0;
}

在Bootply http://www.bootply.com/1vcS8aufxj

中查看此内容

希望这有帮助