Skip to content

Instantly share code, notes, and snippets.

@kazuooooo
Created August 16, 2021 05:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuooooo/58dfe8a12c35ce53f9af08a3141214b4 to your computer and use it in GitHub Desktop.
Save kazuooooo/58dfe8a12c35ce53f9af08a3141214b4 to your computer and use it in GitHub Desktop.
STUDIOに目次をつけるコード
var assignMokuji = function(){
/**
* 指定したテキストでH1もしくはH2要素を見つける
* @param {*} text
* @returns
*/
var findH1OrH2ByText = function(text) {
var h1 = $("h1:contains(" + text + ")").first()
if(h1[0]){
return h1[0]
}
var h2 = $("h2:contains(" + text + ")").first()
if(h2[0]){
return h2[0]
}
return null
}
// 目次を見つける
var mokujiDom = findH1OrH2ByText("目次")
// 目次の各要素に対して内部リンクを貼る
var mokujiUl = mokujiDom.nextElementSibling
var mokujiLi = Array.prototype.slice.call(mokujiUl.children)
mokujiLi.forEach(function(li) {
// リンク先になるタイトル要素
var targetH = findH1OrH2ByText(li.textContent)
if(targetH){
// タイトル要素にIDを付与
var targetHUid = targetH.dataset.uid
$("[data-uid=" + targetHUid + "]").attr('id', targetHUid)
// Li要素にリンクを付与
$("[data-uid=" + li.dataset.uid + "]").first().wrapInner("<a href=#" + targetHUid + "></a>")
}
})
}
// 直接ランディングした場合
window.onload = function(){
assignMokuji()
}
// 別ページから遷移してきた場合
// (SPAなのでonLoadがコールされない)
window.history.pushState = function(){
assignMokuji()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment