使用JS為網(wǎng)頁制作菜單
corepress主題,在文章中允許顯示菜單,如圖。
并且點(diǎn)擊標(biāo)題能實(shí)現(xiàn)跳轉(zhuǎn)到文章指定的標(biāo)題位置,同時(shí)文章目錄菜單的標(biāo)題會(huì)顯示當(dāng)前標(biāo)題顏色
下面記錄一下如何制作的。
枚舉標(biāo)題
通過JQuery,枚舉文章內(nèi)容中的h2標(biāo)簽,并且給標(biāo)簽打上自定義熟屬性。
并且,給目錄面板生成目錄標(biāo)題
$(".post-content h2").each(function () {
$(this).attr('catalog', 'catalog-h2-' + i);
$('#post-catalog-list').append('<p catalog="' + 'catalog-h2-' + i + '" class="catalog-item" onclick="go_catalog(' + "'catalog-h2-" + i + "'" + ')">' + $(this).text() + '</p>');
i++;
});
點(diǎn)擊目錄p標(biāo)簽,執(zhí)行指定方法go_catalog,方法如下
本方法通過查詢文章自定義屬性的標(biāo)題,并且獲取標(biāo)題在文章中的位置,通過animate方法,實(shí)現(xiàn)滾動(dòng)條移動(dòng)
function go_catalog(catalogname) {
var _scrolltop = $('h2[catalog=' + catalogname + ']').offset().top;
$('html, body').animate({
scrollTop: _scrolltop - 60
}, 500
);
}
實(shí)現(xiàn)選中顏色
上述代碼已經(jīng)能實(shí)現(xiàn)文章跳轉(zhuǎn)了,非常簡單,如何實(shí)現(xiàn)對(duì)應(yīng)文章目錄著色比較麻煩。
滾動(dòng)的時(shí)候,瀏覽器有滾動(dòng)事件,我們可以通過判斷第一個(gè)元素是否在可視區(qū)域內(nèi),來實(shí)現(xiàn)顏色作色。
下面代碼實(shí)現(xiàn)了作色功能,首先執(zhí)行set_catalog_css方法,去除鏈接所有選中顏色。
然后再瀏覽器滾動(dòng)事件中,判斷第一個(gè)標(biāo)簽第一個(gè)是否在一個(gè)區(qū)域內(nèi),只要在0-160中,說明已經(jīng)滾動(dòng)到了標(biāo)題位置,進(jìn)行修改css作色
$(document).scroll(function () {
if ($('#post-catalog').css('visibility') != 'visible') {
return;//判斷目錄面板是否可視,不可視則不執(zhí)行下方代碼,免得浪費(fèi)性能
}
$(".post-content h2[catalog]").each(function () {
var el_y = this.getBoundingClientRect().y;
if (el_y < 160 && el_y > 0) {
var name = $(this).attr('catalog');
set_catalog_css();
$('p[catalog=' + name + ']').css('color', ' var(--MaincolorHover)');
return;
}
});
});
function set_catalog_css() {
$('p[catalog]').css('color', 'unset');
}