在滚动条上对齐到Div/Element的顶部 [英] Snap To Top of Div/Element on Scroll
问题描述
在向下滚动页面时,谁能推荐一种最佳"方法将滚动条捕捉到元素顶部?
例如,如果我的布局如下:
<div id="section-one" style="width: 100%; height: 600px;">
Section One
</div>
<div id="section-two" style="width: 100%; height: 600px;">
Section Two
</div>
<div id="section-three" style="width: 100%; height: 600px;">
Section Three
</div>
<div id="section-four" style="width: 100%; height: 600px;">
Section Four
</div>
如果用户正在查看第一部分并开始向下浏览,而第二部分开始进入浏览器视口,则我希望浏览器自动捕捉到下一个div的顶部.
我对.scroll()和.scrollTop很熟悉,但是对从这里去哪里有些不确定.
您可以使用 isScrolledIntoView
检查元素是否在wiewport中.一个由 @Scott Dowding
创建的函数这是一个例子,
$(document).scroll(function() {
$("div:not(.highlight)").each(function() {
if (isScrolledIntoView(this)) {
$("div").removeClass("highlight");
$(this).addClass("highlight");
$("body").animate({ scrollTop: $(this).offset().top }, 1000)
}
});
});
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return (elemTop <= docViewBottom) && (elemTop > docViewTop);
}
Can anyone recommend a "best" approach for snapping the scrollbar to the top of an element when scrolling down a page?
For example, if my layout was as follows:
<div id="section-one" style="width: 100%; height: 600px;">
Section One
</div>
<div id="section-two" style="width: 100%; height: 600px;">
Section Two
</div>
<div id="section-three" style="width: 100%; height: 600px;">
Section Three
</div>
<div id="section-four" style="width: 100%; height: 600px;">
Section Four
</div>
If the user was viewing section one and began browsing down with section two beginning to take part of the browser viewport, I'd like the browser to automatically snap to the top of the next div.
I'm familiar with .scroll() and .scrollTop but a little unsure with where to go from here.
you can check if element is in wiewport with this isScrolledIntoView function created by @Scott Dowding,
And here is an example,
$(document).scroll(function() {
$("div:not(.highlight)").each(function() {
if (isScrolledIntoView(this)) {
$("div").removeClass("highlight");
$(this).addClass("highlight");
$("body").animate({ scrollTop: $(this).offset().top }, 1000)
}
});
});
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return (elemTop <= docViewBottom) && (elemTop > docViewTop);
}
这篇关于在滚动条上对齐到Div/Element的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!