旨在做类似this的事情当您向下滚动时,页面跳转到页面上的 anchor 。一般来说,我不是 JQuery 或 JS 方面的专家(后端语言 PHP 和 MySQL 是我的偏好领域),我抓了几个脚本并将它们放在一起。页面上将有三个 anchor ,因此当您向下滚动时会跳转到下一个 anchor ,当您向上滚动时会跳转到上一个 anchor 。然而,当它滚动到第二个时,即使我没有仍在滚动,它也会不断滚动过去。这是脚本:
var section = 1;
function scrollToAnchor(variable){
var aTag = $("a[name='"+ variable +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
$(function(){
//Keep track of last scroll
var lastScroll = 0;
$(window).scroll(function(event){
//Sets the current scroll position
var st = $(this).scrollTop();
//Determines up-or-down scrolling
if (st > lastScroll && section < 3){
//Going down
section = section + 1;
scrollToAnchor('section'+section);
lastScroll = st;
} else if(st < lastScroll && section > 1){
//Going up
section = section - 1;
scrollToAnchor('section'+section);
lastScroll = st;
}
//Updates scroll position
lastScroll = st;
});
});
还有 fiddle :http://jsfiddle.net/tBN64/4/
最佳答案
原因是,当您滚动
时,scroll事件
被触发,然后animate
函数滚动到该元素,但是动画滚动本身将再次触发滚动事件,从而导致循环。
我建议您尝试不同的方法。例如,您可以捕获鼠标滚轮方向并使用它滚动到下一个元素。
使用 jQuery 鼠标滚轮插件的示例 https://github.com/brandonaaron/jquery-mousewheel
var current_section = 1;
$(window).mousewheel(function (event, delta) {
if (delta > 0) {
current_section = current_section - 1; //up
$('body, html').stop().animate({
scrollTop: $('a[name="section' + current_section + '"]').offset().top
}, 'slow');
} else if (delta < 0) {
current_section = current_section + 1; //down
$('body, html').stop().animate({
scrollTop: $('a[name="section' + current_section + '"]').offset().top
}, 'slow');
}
return false;
});
fiddle :http://jsfiddle.net/tBN64/6/ (以上代码在最后)
注意:此代码不会验证是否有下一个部分
,因此如果滚动太多,则会引发错误。您需要确保下一个元素存在/如果不存在,则不会对其进行动画处理。 (如果您在浏览器中按 F12,通常会看到控制台中的错误)
关于javascript - JQuery 跳转到滚动 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22249099/