【问题标题】:how can I make a div stick to the top of the screen once it's been scrolled to and unstick once it hits the footer?滚动到页脚后如何使 div 粘在屏幕顶部,并在它碰到页脚时取消粘住?
【发布时间】:2014-05-13 19:37:55
【问题描述】:

我找到了this solution 并需要对其进行修改,以便当它碰到页脚时它会松开。 我知道没有scroll_bottom,所以我想尝试为页脚创建一个变量,如下所示。但是,我将继续插电,希望有人可以提供帮助。

$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
    $mainMenuBar = $('#mainMenuBar'),
    $mainMenuBarAnchor = $('#mainMenuBarAnchor');

// Run this on scroll events.
$window.scroll(function() {
    var window_top = $window.scrollTop();
    var window_bottom = $window.height() - this.scrollTop() - this.height(); 
    var div_top = $mainMenuBarAnchor.offset().top;
    if (window_top > div_top) {
        // Make the div sticky.
        $mainMenuBar.addClass('stick');
        $mainMenuBarAnchor.height($mainMenuBar.height());
    }
    else if (window_bottom > div_top) {
     $mainMenuBar.removeClass('stick');
        $mainMenuBarAnchor.height(0);
    }
    else {
        // Unstick the div.
        $mainMenuBar.removeClass('stick');
        $mainMenuBarAnchor.height(0);
    }
});

});

我还找到了this solution,但无法让它与 jquery 1.7 一起使用。

【问题讨论】:

  • 目前无法使用。当它碰到页脚时试图松开。
  • 它在标题中说它应该在点击页脚时松开,不是吗?
  • 对不起。如果它碰到页脚,我需要让“粘性面板” div 不粘。这是我正在进行的工作。 jsfiddle.net/hansoloshotfirst/T4D52/1
  • 像这样:jsfiddle.net/HQS8s/260 ?
  • 啊。是的。谢谢,这行得通。但是,它在我的本地开发站点上出现了奇怪的闪烁。它看起来与动态设置的#mainMenuBarAnchor 高度有关。也许有一种方法可以在不使用#mainMenuBarAnchor 的情况下运行它?无论哪种方式,您的修复都有效,它可能只是我本地站点的问题。你如何选择你的答案作为正确的解决方案?

标签: jquery css sticky


【解决方案1】:

这似乎可以完成工作:

HTML

你说你想要一个不使用#mainMenuBarAnchor的解决方案,所以删除:

<div id="mainMenuBarAnchor"></div>

来自您的 HTML 代码。

JS

$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $menuBarOffset = $mainMenuBar.offset().top,
        window_top = 0,
        footer_offset = $("#footer").offset().top,
        content = $("#content"),
        panel_height = $mainMenuBar.outerHeight()+'px';


    // Run this on scroll events.
    $window.scroll(function() {
        window_top = $window.scrollTop();

        if (window_top >= $menuBarOffset) {
            if (window_top >= footer_offset) {
                // Unstick the div.
                $mainMenuBar.removeClass('stick');
                content.css('margin-top', 0);
            } else {
                // Make the div sticky.
                $mainMenuBar.addClass('stick');
                content.css('margin-top', panel_height);
            }
        }
        else {
            // Unstick the div.
            $mainMenuBar.removeClass('stick');
            content.css('margin-top', 0);
        }
    });
});

现在的代码比以前长了一点,但这主要是因为我在开始时添加了一些变量,这样你就不必在每次滚动时计算一些东西(比如页脚偏移量、菜单栏偏移量.. )。

jsFiddle demo

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 2015-03-05
    • 2017-07-02
    • 2013-07-27
    • 2010-11-16
    • 2017-10-17
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多