[英]Anchor links from external pages don't work when using jQuery smooth scrolling code
我不是 JS 開發人員,我正在使用 Bootstrap 構建一個帶有錨鏈接的單頁站點。
我正在使用我為一些必要功能找到的任何一點點 JS 代碼,例如向錨鏈接添加平滑滾動,頂部偏移,因為我使用的是固定/粘性菜單。
雖然它是一個單頁網站,但我將隱私和條款作為單獨的頁面使用。
這是我用於主頁上的錨鏈接的代碼。 我認為它是 JS 和 jQuery 的混合體。 它運作良好,而且是我想要的方式。
$('.navbar a, .smooth-scroll-contact').on('click', function(event) {
/* Make sure this.hash has a value before overriding default behavior */
if (this.hash !== "") {
/* Prevent default anchor click behavior */
event.preventDefault();
/* Store hash */
var hash = this.hash;
/* Using jQuery's animate() method to add smooth page scroll. */
$('html, body').animate({
scrollTop: $(hash).offset().top - 70
}, 800, function(){
/* Add hash (#) to URL when done scrolling (default click behavior). */
if (history.pushState) {
history.pushState(null, null, hash);
}
else {
window.location.hash = hash;
}
});
} // End if
});
雖然它在主頁上運行良好,但它會阻止在隱私和條款頁面上打開菜單鏈接。 單擊那里的菜單鏈接時,它不會執行任何操作。 它不會轉到主頁或那里的任何錨鏈接。
這是在“隱私”或“條款”頁面上單擊菜單鏈接時出現在控制台中的錯誤:
Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (custom.js:39)
at HTMLAnchorElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLAnchorElement.v.handle (jquery-3.4.1.min.js:2)
第 39 行是scrollTop: $(hash).offset().top - 70
。
我搜索了此錯誤並嘗試應用我發現的一些修復程序,但它們對我不起作用,或者我不知道如何針對此特定代碼正確實現它們。
補充說明:
custom.js
文件在</body>
之前加載;如果您需要更多信息,請告訴我。
經過更多研究,我終於設法找到了解決方案。 這是新代碼,以防其他人遇到同樣的問題:
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
// - 70 is the offset/top margin
$('html, body').animate({
scrollTop: $(hash).offset().top - 70
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior), without jumping to hash
if (history.pushState) {
history.pushState(null, null, hash);
} else {
window.location.hash = hash;
}
});
return false;
} // End if
});
event.preventDefault();
似乎是問題所在,因此已將其刪除。 return false;
加入。
此外,作為獎勵,這里有一個代碼,它允許平滑滾動偏移以錨定來自外部頁面的鏈接:
$(window).on("load", function () {
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length) {
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 70
}, 800);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.