From 6d87a6d54588be5d125aa335f10bf801e71c9593 Mon Sep 17 00:00:00 2001 From: iBug Date: Fri, 6 Sep 2019 15:24:10 +0800 Subject: [PATCH] Add hover links for headings --- _includes/head/custom.html | 1 + assets/css/main.scss | 30 ++++++++++++++++++++++++++++++ assets/js/auto-heading-links.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 assets/js/auto-heading-links.js diff --git a/_includes/head/custom.html b/_includes/head/custom.html index 7c9338b..47deba0 100644 --- a/_includes/head/custom.html +++ b/_includes/head/custom.html @@ -15,4 +15,5 @@ {% endif %} + diff --git a/assets/css/main.scss b/assets/css/main.scss index 12f74a5..79e5d57 100644 --- a/assets/css/main.scss +++ b/assets/css/main.scss @@ -100,3 +100,33 @@ body.landing { } } } + +section.page__content { + h2, h3, h4, h5, h6 { + .header-link { + position: relative; + left: 0.5em; + opacity: 0; + font-size: 0.8em; + -webkit-transition: opacity 0.2s ease-in-out 0.1s; + -moz-transition: opacity 0.2s ease-in-out 0.1s; + -o-transition: opacity 0.2s ease-in-out 0.1s; + transition: opacity 0.2s ease-in-out 0.1s; + } + + &:hover .header-link { + opacity: 1; + } + } +} + +.sr-only { // Screen reader only + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} diff --git a/assets/js/auto-heading-links.js b/assets/js/auto-heading-links.js new file mode 100644 index 0000000..5aed62e --- /dev/null +++ b/assets/js/auto-heading-links.js @@ -0,0 +1,31 @@ +var anchorForId = function (id) { + var anchor = document.createElement("a"); + anchor.className = "header-link"; + anchor.href = "#" + id; + anchor.innerHTML = "Permalink"; + anchor.title = "Permalink"; + return anchor; +}; + +var linkifyAnchors = function (level, containingElement) { + var headers = containingElement.getElementsByTagName("h" + level); + for (var h = 0; h < headers.length; h++) { + var header = headers[h]; + + if (typeof header.id !== "undefined" && header.id !== "") { + header.appendChild(anchorForId(header.id)); + } + } +}; + +document.onreadystatechange = function () { + if (this.readyState === "complete") { + var contentBlock = document.getElementsByClassName("page__content")[0]; + if (!contentBlock) { + return; + } + for (var level = 1; level <= 6; level++) { + linkifyAnchors(level, contentBlock); + } + } +};