【问题标题】:fixed div on bottom of page that stops in given place固定页面底部的 div 停止在给定位置
【发布时间】:2011-02-28 11:35:36
【问题描述】:

我在页面底部固定了 div,效果很好。我想知道当用户向下滚动到页面时,是否有一些简单的方法可以让它在页面的某个位置“停止”。我希望它保持固定在底部,直到用户向下滚动到页面上某个定义的位置,然后将其粘贴到页面上并像其他内容一样滚动。有什么建议吗?

【问题讨论】:

  • 您的意思是(修改)Chromium 问题页面上的内容吗? (例如code.google.com/p/chromium/issues/detail?id=75)请注意左窗格在您向下滚动时保持可见。如果我没记错的话,您希望它稍有不同,但希望对您有所帮助。
  • 是的,它看起来像是我可以使用的东西。我会研究一下,也许我可以让它按照我需要的方式工作。感谢回复!

标签: javascript html css


【解决方案1】:

我尝试在 jsfiddle 上设置一些东西。在我写它的时候,我看到其他人已经发布了他们的替代方案。如果我的有任何帮助:http://jsfiddle.net/PnUmM/1/

我在 CSS 中将位置设置为相对,计算它在文档加载时的位置以将信息放在一边,然后将其设置为固定。

var sticky_offset;
$(document).ready(function() {

    var original_position_offset = $('#sticky_for_a_while').offset();
    sticky_offset = original_position_offset.top;
    $('#sticky_for_a_while').css('position', 'fixed');


});

$(window).scroll(function () {
    var sticky_height = $('#sticky_for_a_while').outerHeight();
    var where_scroll = $(window).scrollTop();
    var window_height = $(window).height();


    if((where_scroll + window_height) > sticky_offset) {
        $('#sticky_for_a_while').css('position', 'relative');
    }

    if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
        $('#sticky_for_a_while').css('position', 'fixed');
    }

});

【讨论】:

  • 是的,这里的答案很快就来了 :-) 但无论如何感谢您的尝试,我明白了
  • 好吧,我终于有时间尝试这个了,我不得不将它重写为纯 js,因为我不能在这上面使用 jQuerry,但它现在就像魅力一样。谢谢。
  • 嗨,这也适用于我。但是,我需要在向下滚动页面时将其附加到屏幕顶部,而不是附加到底部。任何想法?
【解决方案2】:

这是我为你编造的:http://jsfiddle.net/XCYFG/1/。

$(document).ready(function() {
    window._div1 = $('#div1'); //selector is expensive
    window._window = $(window);
    $(window).scroll(function(e) {
        _div1.css("top",
                  Math.min(_window.height(),
                           window.scrollY + 100)
                  + _window.height() - _div1.height() - 110);
    }).scroll();
});

【讨论】:

  • 这看起来很酷,但我可以用另一个 div 的位置来控制它吗?我的意思是——当我向下滚动查看“那个”div 时,开始滚动这个?从简要看一下您的代码,div开始滚动的那一刻是以像素为单位定义的,但是我在每个页面上都会有不同数量的内容,所以我每次都需要调整它......但是再想一想,我可以得到那个位置由 js 生成 div 而不是将值插入到您的脚本中,对吗?
【解决方案3】:

我有一个相反的插件——它在网页的流程中,当用户滚动过去时,它会固定在视口上。它实际上所做的是将一个 css 类应用于元素,因此您应该能够按原样使用它。

你可以在这里找到插件: https://github.com/hanssonlarsson/jquery-fixedscroll

那么我建议你在你的网页流中加入你的元素:

<div id="sometimesFixed">content</div>

使用 css:

#sometimesFixed {
  position: fixed;
  bottom: 0;
}
#sometimesFixed.scroll {
  position: static;
}

然后像这样在你的 JavaScript 中应用插件:

$('#sometimesFixed').fixedscroll({className: 'scroll'});

还有一个更通用的插件,非常新,叫做 jquery-waypoints。这个想法是将任何代码绑定到“航点”,即网页上的点,当用户滚动经过它们时,会执行一些代码。

https://github.com/imakewebthings/jquery-waypoints

它可能比我的插件更优化和更适合,但是 YMMV!

【讨论】:

  • 很好,但是这次我恐怕不能使用jquery,我们不会在我们的项目中使用它。我必须想办法用dojo或纯js来做。不过还是谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-07-30
  • 2020-10-16
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
相关资源
最近更新 更多