【问题标题】:Using scrollTop inside of a fixed element with overflow-y:scroll在具有溢出-y的固定元素内使用scrollTop:scroll
【发布时间】:2014-06-02 09:03:02
【问题描述】:

当我的内容位于指定了 overflow-y: scroll 的固定位置容器内时,我似乎无法让 scrolltop 工作。

这是我的相关代码:

/* some container with many large content blocks inside */
#container {
    position: fixed;
    width: 300px;
    height: 300px;
    overflow-y: scroll;
}

/* button that has a data-path attribute that specifies where the container should scroll to*/
$(".button").on("click", function(){
    var path = $(this).attr("data-path");
    var anchor = $("#" + path);
    var position = anchor.position().top;
    $("#container").animate({scrollTop: position});
});

我相信这个小提琴很好地说明了我的困境:http://jsfiddle.net/Qndu5/

如果你从上向下滚动到一个元素,效果很好。在那之后,所有的赌注都被取消了。它完全无法从顶部以外的任何位置滚动。它要么严重错过了标记,要么一直滚动到顶部,即使提供给它的位置值似乎是正确的。

我当然在这里遗漏了一些东西,但我不确定我不理解什么。感谢您提供的任何帮助!

【问题讨论】:

    标签: javascript jquery html css css-position


    【解决方案1】:

    你在计算位置时缺少的是scrollTop,所以如果视图已经滚动,则需要将其添加到计算中var position = anchor.position().top + $("#container").scrollTop();

    http://jsfiddle.net/x36Rm/

    【讨论】:

    • 完美!我不明白 scrollTop 需要绝对位置而不是相对位置。我使用 position() 是因为担心 scrollTop 不会为溢出的固定容器中的元素返回正确的值。我很高兴解决方案如此简短。感谢您的帮助。
    • 完美答案,你拯救了我的一天!
    • 有没有办法在没有动画的情况下做到这一点?
    • 迟到的答案,但如果我记得我的 jQuery 正确,请用 $("#container").scrollTop(position); 替换 $("#container").animate({scrollTop: position}); 以供将来参考
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多