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

我的未来我决定 提交于 2019-12-22 09:49:31

问题


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.

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/

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!


回答1:


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();

http://jsfiddle.net/x36Rm/



来源:https://stackoverflow.com/questions/23144191/using-scrolltop-inside-of-a-fixed-element-with-overflow-yscroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!