问题描述
当我的内容位于具有溢流y的固定位置容器中时,我似乎无法使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/
如果从上向下滚动到某个元素,则效果很好.在那之后,所有的赌注都关闭了.它完全不能从顶部以外的任何位置滚动.即使输入的位置值看似正确,它还是可怕地错过了标记,或者一直滚动到顶部.
当然我在这里遗漏了一些东西,但是我不确定我不了解什么.感谢您提供的任何帮助!
计算位置时缺少的是scrollTop,因此,如果视图已经滚动,则需要将其添加到计算var position = anchor.position().top + $("#container").scrollTop();
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!
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();
这篇关于在带有溢出y:scroll的固定元素内使用scrollTop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!