Skip to content

Commit

Permalink
如果文章中没有标题属性,则不创建TOC
Browse files Browse the repository at this point in the history
  • Loading branch information
Meekdai committed Jul 29, 2024
1 parent f733212 commit 15d5ea1
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions plugins/GmeekTOC.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@ function createTOC() {
var tocElement = document.createElement('div');
tocElement.className = 'toc';
var contentContainer = document.getElementById('content');
contentContainer.prepend(tocElement);

const headings = contentContainer.querySelectorAll('h1, h2, h3, h4, h5, h6');

if (headings.length === 0) {
return; // 如果没有标题元素,则不创建TOC
}

tocElement.insertAdjacentHTML('afterbegin', '<div class="toc-title">文章目录</div>');

headings.forEach(heading => {
if (!heading.id) {
heading.id = heading.textContent.trim().replace(/\s+/g, '-').toLowerCase();
Expand All @@ -16,10 +22,11 @@ function createTOC() {
link.style.paddingLeft = `${(parseInt(heading.tagName.charAt(1)) - 1) * 10}px`;
tocElement.appendChild(link);
});

tocElement.insertAdjacentHTML('beforeend', '<a href="#" class="toc-end" onclick="window.scrollTo({top:0,behavior: \'smooth\'});">Top</a>');
contentContainer.prepend(tocElement);
}


document.addEventListener("DOMContentLoaded", function() {
createTOC();
var css = `
Expand Down Expand Up @@ -89,4 +96,4 @@ document.addEventListener("DOMContentLoaded", function() {
};

console.log("\n %c GmeekTOC Plugins https://github.com/Meekdai/Gmeek \n","padding:5px 0;background:#C333D0;color:#fff");
});
});

0 comments on commit 15d5ea1

Please sign in to comment.