【问题标题】:Fixed div inside other div after certain scroll在某些滚动后修复了其他 div 内的 div
【发布时间】:2014-04-18 15:33:16
【问题描述】:

我在另一个 div 中有一个 div,如下所示:

<div class="parent">
<div class="child">Text</div>
</div>

我想用 jQuery 将 child 固定在他的父级中。我尝试过这样的事情:

$(document).scroll(function() {
var y = $(document).scrollTop();

if(y >= $(".child").offset().top)  {
        $(".child").css("position", "fixed");
    } else {
        $(".child").css("position", "relative");
    }
});

但它(显然)只是让它修复。我想让它固定,直到它“击中”他父母的底部边框。我该怎么办?

编辑:小提琴:http://jsfiddle.net/8T7Hr/

【问题讨论】:

标签: javascript jquery html scroll fixed


【解决方案1】:
var parent_top = $(".parent").offset().top;
var parent_bottom = $(".parent").offset().top + $(".parent").height() - $(".child").height();

$(document).scroll(function() {
  var y = $(document).scrollTop();

  if(y >= parent_top && y <= parent_bottom)  {
    $(".child").css({"position": "fixed", "top" : "0px"});
  } else {
    $(".child").css("position", "relative");
  }
});

FIDDLE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2012-06-01
    相关资源
    最近更新 更多