滚动固定div到某一点

时间:2012-04-23 11:42:25

标签: jquery

我已经看到了一些这样的例子,但我的情况有点不同,无法弄明白。

我正在使用在这些论坛上找到的一个jQuery,使用'scrollTop'将固定的div滚动到某个点然后停止。

var windw = this;

$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 40
            });
        }
    });
};

$('#scrollto-menu-nav').followTo(250);

但是,当它从底部而不是顶部达到高度时,我需要它停止滚动。有什么想法吗?

谢谢, [R

1 个答案:

答案 0 :(得分:2)

你可以这样做:

<强> HTML

<img src=//ph.artsinn.de alt>
<div>
    <p>A short line of text, for better interpretation.</p>
    <p>Followed by another line, filled with letter and words</p> 
</div>

<img src=//ph.artsinn.de/240x160/666?text=scroll%20down alt id=obj>

<img src=//ph.artsinn.de alt>
<img src=//ph.artsinn.de alt>
<img src=//ph.artsinn.de alt class=end>

<div>
    <p>A short line of text, for better interpretation.</p>
    <p>Followed by another line, filled with letter and words</p> 
</div>

<img src=//ph.artsinn.de alt>
<img src=//ph.artsinn.de alt>
<img src=//ph.artsinn.de alt>
<img src=//ph.artsinn.de alt>​

<强> CSS

/* not needed */
html,body{height:200%}
img {display:block}​

<强> JS

$(function() {
    var $window = $(window),
        $sidebar = $("#obj"),
        sidebarTop = $sidebar.position().top,
        sidebarHeight = $sidebar.height(),
        $footer = $(".end"),
        footerTop = $footer.position().top;

    $sidebar.css('position', 'fixed');
    $window.scroll(function(e) {
        scrollTop = $window.scrollTop();
        topPosition = Math.max(0, sidebarTop - scrollTop);
        topPosition = Math.min(topPosition, (footerTop - scrollTop) - sidebarHeight);
        $sidebar.css('top', topPosition);
    });
});​

而且,再次,fiddle