[英]JQuery Jump to Anchors on Scroll
旨在執行與此類似的操作,其中當您向下滾動時,頁面跳至頁面的錨點。 我一般都不是JQuery或JS的專家(我偏愛后端語言PHP和MySQL),我抓了幾個腳本並將它們放在一起。 頁面上將有三個錨點,因此,當您向下滾動時,它跳到下一個;當您向上滾動時,它跳到下一個。 但是,當滾動到第二個滾動條時,即使我還沒有滾動,它也會繼續滾動經過它。 這是腳本:
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;
});
});
和小提琴: http : //jsfiddle.net/tBN64/4/
原因是,當您scroll
將觸發scroll event
,然后將animate
功能滾動至該元素,但是該動畫滾動本身將再次觸發滾動事件,從而導致循環。
我建議您嘗試另一種方法。 例如,您可以捕獲鼠標滾輪的方向,並使用該方向滾動到下一個元素。
使用jQuery Mousewheel插件的示例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;
});
小提琴: http : //jsfiddle.net/tBN64/6/ (上面的代碼位於結尾)
注意:此代碼不會驗證是否有下section
,因此,如果滾動到太多內容,將拋出錯誤。 您需要確保下一個元素存在/如果不存在動畫。 (有關錯誤,請參閱控制台,通常是在瀏覽器中按F12鍵)
您的腳本中還有更多問題。 首先-我認為您需要防止scroll事件的默認行為,否則它將滾動,並且您不希望這樣做,因為您希望自己動畫化滾動。
event.preventDefault()
可能會有所幫助,並且return false;
在函數的末尾。
那么問題是,滾動事件不會觸發一次,而是一次鼠標滾動會觸發更多次。 您需要以某種方式防止這種情況發生,否則,滾動開始,然后動畫開始,但是滾動仍在繼續,它經過第2節,並一次又一次觸發。
也許這個腳本可以幫上忙-它使新事件scrollStopped
:
通常,我建議您最好搜索執行此行為的腳本,因為您自己進行編程可能會給您帶來很多其他用戶過去在其插件中已解決的問題。
我發現使用Spokey的答案有一些錯誤,當頁面滾動太多時,我們會遇到js錯誤,因此我添加了一些檢查:如果該部分是最后一個,則無需增加其編號,向上滾動時也相同。
我得到了這段代碼,但更改了部分,而不是錨點:
var current_section = 1;
var min_section = 1;
var max_section = $("section[name]").length;
$(window).mousewheel(function (event, delta) {
if (delta > 0) {
current_section = current_section - 1; //up
if (current_section < min_section) current_section = min_section;
$('body, html').stop().animate({
scrollTop: $('section[name="section' + current_section + '"]').offset().top - 100
}, 'slow');
} else if (delta < 0) {
current_section = current_section + 1; //down
if (current_section > max_section) current_section = max_section;
$('body, html').stop().animate({
scrollTop: $('section[name="section' + current_section + '"]').offset().top - 100
}, 'slow');
}
return false;
});
$('body, html').scroll(function(){ return false; }); // allow no scrolling
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.