jQuery 将元素滚动到可滚动容器中的视图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20101059/
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
Scroll element into view in scrollable container
提问by CLiown
I have a scrolling container with a hard coded height:
我有一个硬编码高度的滚动容器:
.scrollingContainer {
overflow: scroll;
height: 400px;
}
This scrolling container contains a list of items, when I click on the item I want to scroll the container so that the item clicked is at the top of the scrolling container.
这个滚动容器包含一个项目列表,当我点击项目时,我想滚动容器,以便点击的项目位于滚动容器的顶部。
$('.scrollingContainer li a').click( function(event) {
var vpHeight = $('.scrollingContainer').height();
var offset = $(this).offset();
$('.scrollingContainer').animate({
scrollTop: vpHeight - offset.top
}, 500);
});
Above is what I have currently, I'm having trouble with the mathematical calculation I need to perform. Also I think the var offset
value is incorrect as it seems to be getting the offset from the top of the page where I was hoping to get the offset value based on it's position in the scrolling container.
以上是我目前所拥有的,我在进行需要执行的数学计算时遇到了问题。此外,我认为该var offset
值不正确,因为它似乎是从页面顶部获取偏移量,我希望根据它在滚动容器中的位置来获取偏移量值。
Any help appreciated!
任何帮助表示赞赏!
回答by isherwood
A variation of this answerdoes the trick:
var myContainer = $('.scrollingContainer')
$(myContainer).on('click', 'a', function () {
var scrollTo = $(this);
myContainer.animate({
scrollTop: scrollTo.offset().top - myContainer.offset().top + myContainer.scrollTop()
});
});
回答by Nate
Here's a live example: http://jsfiddle.net/LqQGR/12/
这是一个活生生的例子:http: //jsfiddle.net/LqQGR/12/
You want to set your scrollTop to the element's position (the distance between the top of the container and the link) plusthe current scrollTop (the distance between the top of the containedcontent and the current place it's visible.
您希望将 scrollTop 设置为元素的位置(容器顶部与链接之间的距离)加上当前 scrollTop(所包含内容的顶部与其可见的当前位置之间的距离)。
Also: you need to set your scrollingContainer to position: relative
so that it's the offset parentof the content within.
另外:您需要将 scrollingContainer 设置为position: relative
,使其成为其中内容的偏移父级。
var $scrollingContainer = $('.scrollingContainer');
$scrollingContainer.on('click', 'a', function (event) {
var scrollTop = $scrollingContainer.scrollTop();
var link = $(event.currentTarget);
var position = link.position();
$scrollingContainer.animate({
scrollTop: position.top + scrollTop
}, 500);
});
By the way, my answer is superior to one in which you add click event listeners to all anchor tags individually. This only adds one listener, which is more performant. Read more about delegated events
顺便说一句,我的答案优于将点击事件侦听器单独添加到所有锚标记的答案。这只添加了一个监听器,性能更高。阅读有关委托事件的更多信息