滚动后将元素粘贴到顶部

时间:2011-08-13 20:16:54

标签: javascript jquery html css

我想在侧边栏中移动/跟随容器/ div以及页面向下滚动。它不仅仅是一个position:fixed容器。它只会在向下滚动时消失。实施的最佳做法是什么?

谢谢

1 个答案:

答案 0 :(得分:4)

说我们想要:

  1. 从顶部开始260px(在CSS中定义)
  2. 坚持,从顶部24px(在JS中定义)
  3. var $sticky = $("#sticky"),
        pos = {
          abs : {position: "absolute",  top: parseInt($sticky.css("top"), 10) },
          fix : {position: "fixed",     top: 24 /* <<< SET AS DESIRED */ },
        };
    
    $(window).on("load scroll", function() {
      var canFix = $(this).scrollTop() >= pos.abs.top - pos.fix.top;
      $sticky.css( pos[ canFix? "fix" : "abs" ] );
    });
    body{
      height: 2000px;
      border: 4px dashed #444;
    }
    #sticky{
      height: 100px;
      background: #0bf;
      position:absolute;
      top: 260px;   /* <<< SET AS DESIRED */
    }
    SCROLL!
    <div id="sticky">STICK ME AT 24 FROM TOP</div>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>