jquery animate/scrollTop 到 div 内的多个锚点

jquery animate/scrollTop to multiple anchors inside divs

我在我的页面上实现相对复杂的自动滚动功能时遇到了问题。这显示了我的代码中的问题...

http://codepen.io/d3wannabe/pen/XXxdQq

我的页面上有多个 div(在我的示例中为蓝色、红色、绿色),我不仅希望能够滚动到它们(我示例中的前 3 个按钮完美实现) ,但我希望能够在内部滚动(底部的 3 个按钮代表我的最佳尝试)。

我想不通的是,为什么 scroll within 功能在我的第一个 div("scrollTo3rdBlueItem" 按钮上运行良好,但在另一个 [=29= 上却不太准确]s("scrollTo3rdRedItem" 和 "scrollTo3rdGreenItem" 按钮)。在我的完整 Web 应用程序(显然有更多数据可以滚动浏览)中,我基本上看到父 div 位于页面的下方,我在其中滚动的准确性越低。

虽然我很难确定大部分模式,但不能简单地尝试调整偏移值。任何我在这里可能做错的想法都将不胜感激!!

...因为我不允许在不引用代码的情况下 post 这个 - 这是 jquery 您可以在我的 codepen 中看到的函数!

function scrollToParent(parentID){
        $('html,body').animate({scrollTop: $('#'+parentID).offset().top}, 500);
 }
function scrollToChild(parentID, childID){
      //first focus on the parent
  scrollToParent(parentID);

      $('#'+parentID).animate(
        {scrollTop: $('#'+ childID).offset().top - 100}
        , 500);
}

更新

这里的回答完全错误。留在这里以保留评论。

更新 2

知道了!您需要考虑父级 div 的偏移量。将 scrollToChild 函数更新为以下内容;

  $('#'+parentID).animate(
    {
      scrollTop: $('#'+ childID).offset().top - $('#'+parentID).offset().top
    }, 500);