最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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: /

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!

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!

Share Improve this question asked Apr 17, 2014 at 21:59 addMittaddMitt 1,0212 gold badges15 silver badges27 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

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/

发布评论

评论列表(0)

  1. 暂无评论