From 9ae86f5999099f1578442a4ea7c86ad243660817 Mon Sep 17 00:00:00 2001 From: duzhao Date: Thu, 1 Feb 2018 20:17:57 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=8A=A0=E5=AF=86=E6=96=87?= =?UTF-8?q?=E7=AB=A0=E5=AF=BB=E6=89=BE=E4=B8=8D=E5=88=B0Toc=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/js/main.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/source/js/main.js b/source/js/main.js index f07b28e2..b3eee681 100644 --- a/source/js/main.js +++ b/source/js/main.js @@ -110,7 +110,10 @@ headerH = header.clientHeight, titles = $('#post-content').querySelectorAll('h1, h2, h3, h4, h5, h6'); - toc.querySelector('a[href="#' + titles[0].id + '"]').parentNode.classList.add('active'); + var firstLink = titles.length > 0 ? toc.querySelector('a[href="#' + titles[0].id + '"]') : toc.querySelectorAll('a')[0]; + + if (firstLink) + firstLink.parentNode.classList.add('active'); // Make every child shrink initially var tocChilds = toc.querySelectorAll('.post-toc-child'); @@ -118,8 +121,7 @@ tocChilds[i].classList.add('post-toc-shrink'); } var firstChild = - toc.querySelector('a[href="#' + titles[0].id + '"]') - .nextElementSibling; + firstLink.nextElementSibling; if (firstChild) { firstChild.classList.add('post-toc-expand'); firstChild.classList.remove('post-toc-shrink'); @@ -152,6 +154,11 @@ top >= bannerH - headerH ? toc.classList.add('fixed') : toc.classList.remove('fixed'); }, actived: function (top) { + + if (titles.length == 0) { + titles = $('#post-content').querySelectorAll('h1, h2, h3, h4, h5, h6'); + } + for (i = 0, len = titles.length; i < len; i++) { if (top > offset(titles[i]).y - headerH - 5) { var prevListEle = toc.querySelector('li.active'); @@ -161,7 +168,7 @@ } } - if (top < offset(titles[0]).y) { + if (titles.length > 0 && top < offset(titles[0]).y) { handleTocActive( toc.querySelector('li.active'), toc.querySelector('a[href="#' + titles[0].id + '"]').parentNode