可滚动面板捕捉到滚动上的元素 [英] Scrollable Panel snap to elements on Scroll
问题描述
当用户滚动时,可滚动div中是否有一种方法可以捕捉到元素。
Is there a way inside a scrollable div to snap to elements as the user scrolls.
例如,如果我们有CSS,例如
For example if we have CSS such as
.container {
height: 300px;
width: 200px;
overflow: auto
}
li {
height: 40px;
width: 100 % ;
}
和HTML as
<div class="container">
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
<li>
test
</li>
</div>
因此容器应该有一个垂直滚动条。当用户滚动时我希望它能够在它们停止滚动时最终滚动位置将容器滚动位置捕捉到所示的最近的div。这可能很难,因为像safari这样的浏览器也会提供动力,因此它必须是滚动结束时的事件。
So from that the container should have a vertical scroll bar. When the user scrolls I would like it so that when they stop scrolling the final scroll position snaps the container scroll position to the nearest div at shown. This might be difficult as browsers like safari offer momentum as well, so it would have to be an event on scroll end.
任何想法,如果这是可能的,以及如何。
Any ideas if this is possible, and how.
Marvelous
Marvellous
推荐答案
您可以使用setTimeout。这应该工作
You can use setTimeout. This should work
var snap_timer;
var scroll_from_mouse = true;
function snapList(){
var snapped = false;
var i = 0;
while(!snapped && i < $('.container li').size()){
var itop = $('.container li').eq(i).position().top;
var iheight = $('.container li').eq(i).outerHeight();
if(itop < iheight && itop > 0){
scroll_from_mouse = false;
snapped = true;
var new_scroll_top = 0;
if(iheight - itop > iheight / 2)
new_scroll_top = $('.container').scrollTop() + itop;
else if(i > 1)
new_scroll_top = $('.container').scrollTop() - ($('.container li').eq(i-1).outerHeight() - itop);
else
new_scroll_top = 0;
$('.container').scrollTop(new_scroll_top);
}
i++;
}
};
$(function(){
$('.container').scroll(function(){
clearTimeout(snap_timer);
if(scroll_from_mouse) snap_timer = setTimeout(snapList, 200);
scroll_from_mouse = true;
});
});
这篇关于可滚动面板捕捉到滚动上的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!