开发者

Problem with fixed/following sidebar

开发者 https://www.devze.com 2023-02-09 11:52 出处:网络
I\'m trying to create a sidebar which follows the user when he scrolls down the page and I managed to accomplish the effect using the following code:

I'm trying to create a sidebar which follows the user when he scrolls down the page and I managed to accomplish the effect using the following code:

Markup

<div id="contentWrapper">
    <div id="lcWrapper">
        <div class="editor_left" id="leftCo开发者_JS百科lumn" data-id="">
        </div>
    </div>
    <!-- other divs (central and right column) -->
    <div style="clear: both;"></div>
</div>

Javascript

var $sidebar   = $("#leftColumn"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            }, 300);
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            }, 300);
        }
    });

It works just fine but I still have a problem: when I scroll down through the page, the sidebar should stop following me if I've reached the end of the page; what happens with this code is that instead of just stopping the sidebar from moving further down when I reach the end of the page, its container gets "stretched" (its height increases) and I can continue scrolling down as much as I want (actually I can't pratically reach the end of the page since some extra space gets always added when I scroll down).

I hope you get the problem, I don't know if I've been clear enough. I know this could be solved by doing a check on the position and height of the column in the scroll event handler, but I hoped there was a simple solution using CSS settings?

Any help?


I am not sure why you chose a jQuery solution from the moment you can use a pure css solution like #leftColumn {position:fixed;top:0;} You can find more information about css position and fixed value at http://www.w3.org/TR/CSS2/visuren.html#propdef-position

An example of the above css suggestion you can find here: http://jsbin.com/onefa4


If you position the sidebar absolutely (position:absolute), and the container (closest parent, #lcWrapper and/or #contentWrapper) that has position:relative) has default overflow (overflow:static) the container size shouldn't change and the sidebar should stay visible. In this case you'd animate the CSS top-property (like top:300px).

In this case CSS should be something like

#contentWrapper {position:relative;}
#leftColumn {position:absolute; top: 100px;}
0

精彩评论

暂无评论...
验证码 换一张
取 消