我想创建一个div,它位于一个内容块的下面,但一旦页面已经滚动到足以接触其顶部边界,就会固定在原地并与页面滚动。


当前回答

在javascript中,你可以做:

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";

其他回答

您已经在谷歌Code的发行页面和Stack Overflow的编辑页面上看到过这个例子。

当你向上滚动时,CMS的答案不会恢复定位。以下是从Stack Overflow窃取的无耻代码:

function moveScroller() {
    var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');

    var move = function() {
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "0px"
            });
        } else {
            $scroller.css({
                position: "relative",
                top: ""
            });
        }
    };
    $(window).scroll(move);
    move();
}
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>

<script type="text/javascript"> 
  $(function() {
    moveScroller();
  });
</script> 

还有一个简单的现场演示。

一个新兴的、无脚本的替代方案是position: sticky, Chrome、Firefox和Safari都支持它。请参阅HTML5Rocks和demo上的文章以及Mozilla文档。

我和你有同样的问题,最终制作了一个jQuery插件来解决它。它实际上解决了人们在这里列出的所有问题,而且还增加了一些可选特性。

选项

stickyPanelSettings = {
    // Use this to set the top margin of the detached panel.
    topPadding: 0,

    // This class is applied when the panel detaches.
    afterDetachCSSClass: "",

    // When set to true the space where the panel was is kept open.
    savePanelSpace: false,

    // Event fires when panel is detached
    // function(detachedPanel, panelSpacer){....}
    onDetached: null,

    // Event fires when panel is reattached
    // function(detachedPanel){....}
    onReAttached: null,

    // Set this using any valid jquery selector to 
    // set the parent of the sticky panel.
    // If set to null then the window object will be used.
    parentSelector: null
};

https://github.com/donnyv/sticky-panel

演示:http://htmlpreview.github.io/?https: / / github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

接受的答案是有效的,但如果你在上面滚动,它不会回到之前的位置。它总是粘在顶部后,放在那里。

  $(window).scroll(function(e) {
    $el = $('.fixedElement');
    if ($(this).scrollTop() > 42 && $el.css('position') != 'fixed') {
      $('.fixedElement').css( 'position': 'fixed', 'top': '0px');

    } else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
      $('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
//this was just my previous position/formating
    }
  });

jleedev的响应应该工作,但我不能让它工作。他的示例页面也不起作用(对我来说)。

这是另一种选择:

JAVASCRIPT

var initTopPosition= $('#myElementToStick').offset().top;   
$(window).scroll(function(){
    if($(window).scrollTop() > initTopPosition)
        $('#myElementToStick').css({'position':'fixed','top':'0px'});
    else
        $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});

你的#myElementToStick应该以position:absolute CSS属性开始。

以下是Josh Lee的回答的扩展版本。如果你想让div在侧边栏的右边,并浮动在一个范围内(即,你需要指定顶部和底部锚位置)。它还修复了一个bug,当你在移动设备上查看这个(你需要检查左滚动位置,否则div将移出屏幕)。

function moveScroller() {
    var move = function() {
        var st = $(window).scrollTop();
        var sl = $(window).scrollLeft();
        var ot = $("#scroller-anchor-top").offset().top;
        var ol = $("#scroller-anchor-top").offset().left;
        var bt = $("#scroller-anchor-bottom").offset().top;
        var s = $("#scroller");
        if(st > ot) {
            if (st < bt - 280) //280px is the approx. height for the sticky div
            {
                s.css({
                    position: "fixed",
                    top: "0px",
                    left: ol-sl
                }); 
            }
            else
            {
                s.css({
                    position: "fixed",
                    top: bt-st-280,
                    left: ol-sl
                }); 
            }
        } else {
            s.css({
                position: "relative",
                top: "",
                left: ""
            });

        }
    };
    $(window).scroll(move);
    move();
}