2014-10-29 33 views
1

我是Jquery的新手,想更好地理解。瞭解Jquery代碼以突出顯示navbar項目

我正在使用引導滾動間諜來改變我的導航突出顯示,因爲我不斷滾動頁面或當我點擊特定鏈接,現在默認插件在引導不是非常可定製的,所以我搜索了stackoverflow,發現一個偉大的完美的代碼和平。雖然目前的要求是這樣的,我將不得不進一步修改此代碼以適應我的需求。但我無法理解開發人員給出的完整代碼。

原始的jsfiddle Jsfiddle

下面

是代碼。

enter code here $(document).ready(function() { 
$(document).on("scroll", onScroll); 

//smoothscroll 
$('a[href^="#"]').on('click', function (e) { 
    e.preventDefault(); 
    $(document).off("scroll"); 

    $('a').each(function() { 
     $(this).removeClass('active'); 
    }) 
    $(this).addClass('active'); 

    var target = this.hash, 
     menu = target; 
    $target = $(target); 
    $('html, body').stop().animate({ 
     'scrollTop': $target.offset().top+2 
    }, 500, 'swing', function() { 
     window.location.hash = target; 
     $(document).on("scroll", onScroll); 
    }); 
    }); 
}); 

function onScroll(event){ 
var scrollPos = $(document).scrollTop(); 
$('#menu-center a').each(function() { 
    var currLink = $(this); 
    var refElement = $(currLink.attr("href")); 
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { 
     $('#menu-center ul li a').removeClass("active"); 
     currLink.addClass("active"); 
    } 
    else{ 
     currLink.removeClass("active"); 
    } 
    }); 
} 

現在我通過這個代碼去了,我看到相當多的jQuery函數中使用,例如在()和關()和的location.hash。所以我去檢查了Jquery文檔,並瞭解了我不熟悉的功能,其中大部分都是有意義的,但有些部分仍然沒有。

$('html, body').stop().animate({ 
     'scrollTop': $target.offset().top+2 
    }, 500, 'swing', function() { 
     window.location.hash = target; 
     $(document).on("scroll", onScroll); 
    }); 

我不知道在上面的代碼中發生了什麼。我瞭解stop()函數的用法。 '擺動'之後爲什麼該功能?那真的在做什麼?

回答

0

animate方法中的最後一個參數是回調;一旦動畫完成,就會調用該匿名函數。

匿名函數

window.location.hash = target; 

的第一行改變URL的散列部,e.g的「#」之後的部分。這保留了後退按鈕的功能。

至於第二線

$(document).on("scroll", onScroll); 

通知大約十幾行以上的地方說:動畫被調用之前

$(document).off("scroll"); 

滾動事件被關閉。所以,匿名函數中的第二行將其重新打開。

+0

是的回調函數確切地說,這就是我想知道的。謝謝 。我明白了on和off的位,並且還注意到onclick()事件處理程序被關閉,並且當回調函數被調用時,事件處理程序再次被附加。 – 2014-10-29 20:57:44

0

.on()添加一個事件處理程序(不太常見,但該標準的一部分)和 .off()刪除它

window.location.hash改變散列後的部分:
window.location.hash = "example"; 生產「www.blah.com/ #示例

$('html, body').stop().animate({ 
    'scrollTop': $target.offset().top+2 
}, 500, 'swing', function() { 

這裏500是動畫的持續時間,'擺動'是動畫的類型,函數是回調wi當動畫完成時將被調用

+0

我完全明白這一點,甚至在我發佈這個問題之前,感謝你的回覆,請再次閱讀我的問題,看看我不明白的部分,我指出了。謝謝 – 2014-10-29 20:51:56

+0

感謝您的編輯。最後一個爲什麼+2的事情,就是那種仁慈的花式數學? – 2014-10-29 21:00:32