[英]scroll to a div when scrolling, and scroll to top when div disappear
我的网页上有2个div。 第一个div是“ #pattern”(红色一个),第二个是“ #projets”。(蓝色一个)
当use第一次滚动时,窗口自动滚动到第二个div“ #projets”。 我正在使用jquery scroll-To插件。 即使用户进行大量滚动,滚动效果也可能很好,但是可能与“ #projets” div偏移了。如果有人有一个更正的想法,那就很好了,但这不是我的主要麻烦。 ..
现在,我尝试滚动到页面顶部(“ #pattern” div),滚动时再次出现“ #pattern” div,红色的。 因此,基本上应该是从div“ #projets”到屏幕顶部的偏移量大于1。
我已经尝试了很多没有结果的解决方案,使用了标志,使用了多个条件...这可能与此页面上的内容相同,但是用户应该有能力在页面内自由滚动,而不是从哈希滚动到哈希:
http://www.thepetedesign.com/demos/onepage_scroll_demo.html
这是我的html:
<div id="pattern"></div>
<div id="projets"></div>
我的CSS:
#pattern {
height:300px;
width: 100%;
background-color:red
}
#projets {
height:800px;
width: 100%;
background-color:blue
}
和我的jQuery:
var flag=0 ;
$(window).on('scroll',function(){
var top_projets_position = $("#projets").offset().top - $(window).scrollTop();
if((flag==0) && $(window).scrollTop()>1){
$(window).scrollTo('#projets', 500);
flag=1;
}
if($(window).scrollTop()==0){
flag=0;
}
});
这是jsfiddle:
希望有人可以帮我解决这个问题,我不知道自己在做什么错,也许是错误的方法! 谢谢
看来您需要跟踪3件事:
var prev_scroll = 0; // <-- to determine direction of scrolling
var current_view ="#pattern"; // <-- to determine what element we are viewing
var allowed = true; // <-- to prevent scrolling confusion during animation
var top_projets_position = $("#projets").offset().top + 1;
$(window).on('scroll',function(){
var current_scroll = $(window).scrollTop();
if(current_scroll < top_projets_position && current_view=="#projets" && current_scroll < prev_scroll){
scrollToTarget("#pattern");
}
if($(window).height() + current_scroll > top_projets_position && current_view=="#pattern" && current_scroll > prev_scroll){
scrollToTarget("#projets");
}
prev_scroll = current_scroll;
});
function scrollToTarget(selector){
if(allowed){
allowed = false;
$(window).scrollTo(selector, {
'duration':500,
'onAfter': function(){ allowed = true; current_view = selector;}
});
}
}
这只是基于原始代码的快速解决方案。 更好的解决方案是执行更多面向对象(OOP)的操作并跟踪对象中的值。 也许在对象创建时采用一系列元素,抓住所有边界,并使用滚动处理程序中的边界来确定何时滚动到下一个div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.