javascript 在带有溢出-y:scroll 的固定元素内使用 scrollTop

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23144191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:25:09  来源:igfitidea点击:

Using scrollTop inside of a fixed element with overflow-y:scroll

javascriptjqueryhtmlcsscss-position

提问by addMitt

I can't seem to get scrolltop to work when my content is inside of a fixed position container that has overflow-y: scroll specified.

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

Here is my relevant code:

这是我的相关代码:

/* 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});
});

I believe this fiddle illustrates my dilemma quite well: http://jsfiddle.net/Qndu5/

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

If you scroll from the top down to an element, it works great. After that, all bets are off. It is completely incapable of scrolling from any position other than the top. It either horribly misses the mark, or scrolls all the way back to the top, even though the position values being fed to it are seemingly correct.

如果您从上向下滚动到某个元素,则效果很好。在那之后,所有赌注都取消了。它完全无法从顶部以外的任何位置滚动。它要么严重错过标记,要么一直滚动到顶部,即使输入的位置值看起来是正确的。

Surely I'm missing something here, but I'm not sure what I am not understanding. Thanks for any help provided!

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

回答by Morten Olsen

What you are missing is the scrollTop when calculating the position, so if the view is already scrolled, that need to be added to the calculation var position = anchor.position().top + $("#container").scrollTop();

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

http://jsfiddle.net/x36Rm/

http://jsfiddle.net/x36Rm/