使用 JavaScript 將深層錨鏈接添加到您的博客
深層錨鏈接,也稱為跳轉鏈接,對於允許用戶共享指向文章特定部分的直接鏈接很有用。它們不僅可以創造更好的用戶體驗,而且還有助於社交媒體共享和直接鏈接到文檔的不同部分。
在本文中,我們將學習如何使用 vanilla JavaScript 將博客文章標題轉換為深層錨鏈接。我們不會為此使用任何第三方插件。
為此,您無需向標題添加 ID 或擔心 URL。事實上,我們將使用標題文本生成 ID 和標題文本旁邊的錨鏈接。已經有了身份證?不用擔心。我們不會改變它們。
HTML 標記
這是我們要添加深層錨鏈接的示例 HTML 標記。
<!DOCTYPE html>
<html lang="en">
<body>
<h1>15 ways food processors are completely overrated</h1>
<time>24 March, 2019</time>
<div class="post-content">
<h2>Introduction</h2>
<p>...</p>
<h2>A Brief History</h2>
<p>...</p>
<h3>Fast Food</h3>
<p>...</p>
<h3>Home Made Food</h3>
<p>...</p>
<h2>Conclusion</h2>
<p>...</p>
</div>
</body>
</html>
如上所示,我們有多個 h2
和 h3
沒有 ID 的標題。我們的目標是將這些標題轉換為深層錨鏈接。
錨鏈接生成
讓我們開始編寫 JavaScript 來實現我們的鏈接生成目標。第一步是根據標題文本生成 ID 和鏈接。下面的 JavaScript 代碼片段完成了這項工作:
document.querySelectorAll('.post-content h1, .post-content h2, .post-content h3, .post-content h4').forEach($heading => {
//create id from heading text
var id = $heading.getAttribute("id") || $heading.innerText.toLowerCase().replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '').replace(/ +/g, '-');
//add id to heading
$heading.setAttribute('id', id);
//append parent class to heading
$heading.classList.add('anchor-heading');
//create anchor
$anchor = document.createElement('a');
$anchor.className = 'anchor-link';
$anchor.href = '#' + id;
$anchor.innerText = '#';
//append anchor after heading text
$heading.appendChild($anchor);
});
上面的 JavaScript 代碼選擇所有 h1
, h2
, h3
和 h4
.post-content
裡面 選擇器。 為什麼選擇這個類選擇器? 因為我們只想在文章內容內部而不是整個頁面中添加指向標題的錨鏈接。
forEach()
是一個 JavaScript 元素方法,它為每個標題調用一次提供的函數。在提供的函數中,首先,我們根據現有的 ID 值或標題文本創建一個 ID。然後使用 setAttribute()
將生成的 ID 添加到標題中 方法。
最後,我們創建一個新的錨元素,設置它的 URL 並顯示文本(#
) 在將其附加到標題文本旁邊之前。簡而言之,如果我們有這樣的標題 <h2>Introduction</h2>
, 會轉換成如下:
<h2 id="introduction" class="anchor-heading">Introduction<a class="anchor-link" href="#introduction">#</a></h2>
您可能還想為新生成的錨鏈接添加平滑滾動。默認情況下,如果您單擊任何此類鏈接,它將突然跳到頂部。您可以使用以下代碼更改此行為,使其成為平滑的滾動過渡。
document.querySelectorAll('a.anchor-link').forEach($anchor => {
$anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth',
block: 'start' //scroll to top of the target element
});
});
});
至此,我們完成了鏈接生成和平滑滾動到頂部。但它僅在頁面完全加載後才有效。如果你想通過在瀏覽器窗口中輸入錨鏈接直接跳到文章的某個部分,我們需要做更多的工作:
if (window.location.hash.length > 0) {
setTimeout(function () {
document.querySelector('a[href="' + window.location.hash + '"]').click();
}, 150);
}
注意 setTimeout()
功能。我們正在使用它來延遲 150ms
的手動導航 以便生成深層錨鏈接並將其添加到 DOM。
最後,讓我們添加一些 CSS 樣式以僅在用戶將鼠標懸停在標題上時顯示深層錨鏈接。這正是我在博客上所做的。如果您將鼠標懸停在任何標題上,您將看到一個錨鏈接。
.anchor-heading .anchor-link {
display: inline-block;
padding-left: .25rem;
text-decoration: none;
opacity: 0;
transition: opacity ease-in-out .25s;
}
.anchor-heading .anchor-link:hover {
opacity: 1 !important;
}
.anchor-heading:hover .anchor-link {
opacity: .5;
}
默認情況下,錨鏈接是不可見的(不透明度為 0
)。當您將鼠標懸停在標題上時,錨鏈接不透明度會增加到 .5
或 50%
.不透明度增加到 100%
當您直接將鼠標懸停在鏈接上時。
獎勵:jQuery 解決方案
如果您已經在您的網站上使用 jQuery,那麼添加深層錨鏈接會更加容易。將上面的 vanilla JavaScript 代碼替換為以下 jQuery 等效代碼:
$(document).ready(function () {
$('.post-content h1, .post-content h2, .post-content h3, .post-content h4').each(function () {
//create id from heading text
var id = $(this).attr('id') || $(this).text().toLowerCase().replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '').replace(/ +/g, '-');
//add id to heading
$(this).attr('id', id);
//append parent class to heading
$(this).addClass('anchor-heading');
//create anchor
var anchor = $('<a class="anchor-link" href="#' + id + '">#</a>');
//append anchor link after heading text
$(this).append(anchor);
});
//add smooth scroll for anchor links
$(document).on('click', 'a.anchor-link', function (e) {
e.preventDefault();
$('html, body').stop().animate({
scrollTop: $($(this).attr('href')).offset().top - 50
}, 1000, 'linear');
});
//navigate to anchor if available
if (window.location.hash.length > 0) {
$('a[href="' + window.location.hash + '"]').trigger('click');
}
});
結論
這就是將博客文章或任何其他 HTML 文檔中的標題轉換為深層錨鏈接的全部內容。我們討論了基於原生 JavaScript 和 jQuery 的解決方案。這不是添加深層錨鏈接的唯一方法。添加此類鏈接還有很多其他創造性的方法。
如果您需要更高級的解決方案(顯示/隱藏圖標、鏈接放置等的更多選項),我推薦使用 anchor.js。它是一個約 6KB 的縮小 JavaScript 文件,可讓您動態添加深層錨鏈接。但是如果您關心網站性能,只需添加以上幾行代碼即可。
如果您有任何問題或建議,請隨時給我發推文。