在div到达页脚之前阻止div跟随滚动

时间:2016-04-30 10:55:05

标签: javascript jquery

我一直在使用以下脚本在页面滚动时使页面上的div向下浮动。

这是剧本:

(function($) {
    var element = $('.follow-scroll'),
        originalY = element.offset().top;

    // Space between element and top of screen (when scrolling)
    var topMargin = 105;

    // Should probably be set in CSS; but here just for emphasis
    element.css('position', 'relative');

    $(window).on('scroll', function(event) {
        var scrollTop = $(window).scrollTop();

        element.stop(false, false).animate({
            top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
        }, 300);
    });
})(jQuery);

这是页面:http://www.wedoblogging.com/faqs/(U:wedoblogging P:cadb7b6c)

正如你所看到的,浮动div(标题为:Ask Us)一直向下滑入页脚,我希望这个div在它到达页脚上方的绿色条之前停止跟随滚动。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

与此规则相似

top: scrollTop < originalY ? 0 : /*following code*/;

添加另一个包含允许的最大位置的规则:

var nextPosition = scrollTop - originalY + topMargin;
var maxPositionAllowed = 450;
top: scrollTop < originalY ? 0 : Math.min(nextPosition, maxPositionAllowed )

因此,无论何时,元素都试图超越maxPostionAllowed,您将强制它与顶部保持距离。我不确定450是否是您想要的值,但您可以看到它的外观有几种不同。

所以它看起来像这样:

(function($) {
    var element = $('.follow-scroll'),
        originalY = element.offset().top;

    // Space between element and top of screen (when scrolling)
    var topMargin = 105;

    // Should probably be set in CSS; but here just for emphasis
    element.css('position', 'relative');

    $(window).on('scroll', function(event) {
        var scrollTop = $(window).scrollTop();
        var nextPosition = scrollTop - originalY + topMargin;
        var maxPositionAllowed = 450;

        element.stop(false, false).animate({
            top: scrollTop < originalY ? 0 : Math.min(nextPosition, maxPositionAllowed)
        }, 300);
    });
})(jQuery);