2

我看过一些这样的例子,但我的有点不同,无法弄清楚。

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

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

4

1 回答 1

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

于 2012-08-12T15:17:10.077 回答