使用带有overflow-y的固定元素内的scrollTop:scroll

add*_*itt 3 html javascript css jquery css-position

当我的内容位于具有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});
});
Run Code Online (Sandbox Code Playgroud)

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

如果从上往下滚动到元素,它会很有效.之后,所有赌注都已关闭.它完全无法从顶部以外的任何位置滚动.它要么可怕地错过了标记,要么一直滚动到顶部,即使输入的位置值看起来是正确的.

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

Mor*_*sen 15

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

http://jsfiddle.net/x36Rm/