diff --git a/sass/copy.scss b/sass/copy.scss new file mode 100644 index 0000000..7f03d95 --- /dev/null +++ b/sass/copy.scss @@ -0,0 +1,32 @@ +.copy-button { + position: absolute; + top: 8px; + right: 8px; + padding: 4px 10px; + font-size: 0.8rem; + font-family: DejaVu Sans Mono, Monaco, Consolas, Ubuntu Mono, monospace; + background: var(--accent); + color: var(--background); + border: none; + border-radius: 3px; + cursor: pointer; + opacity: 0; + transition: opacity 0.2s ease; + z-index: 1; + + &:hover { + opacity: 1; + } + + &.copied { + background: #4caf50; + } +} + +pre:hover .copy-button { + opacity: 0.8; +} + +pre:hover .copy-button:hover { + opacity: 1; +} diff --git a/sass/main.scss b/sass/main.scss index 969188d..45c1566 100644 --- a/sass/main.scss +++ b/sass/main.scss @@ -133,6 +133,7 @@ pre { overflow: auto; border-top: 1px solid rgba(255, 255, 255, .1); border-bottom: 1px solid rgba(255, 255, 255, .1); + position: relative; @media (max-width: $phone-max-width) { white-space: pre-wrap; diff --git a/sass/style.scss b/sass/style.scss index a7400fc..722485f 100644 --- a/sass/style.scss +++ b/sass/style.scss @@ -5,5 +5,6 @@ @import 'main'; @import 'post'; @import 'toc'; +@import 'copy'; @import 'pagination'; @import 'footer'; diff --git a/static/copy.js b/static/copy.js new file mode 100644 index 0000000..07d05c6 --- /dev/null +++ b/static/copy.js @@ -0,0 +1,34 @@ +(function() { + document.querySelectorAll('pre code').forEach((codeBlock) => { + const pre = codeBlock.parentElement; + + if (pre.querySelector('.copy-button')) { + return; + } + + const copyButton = document.createElement('button'); + copyButton.className = 'copy-button'; + copyButton.textContent = '复制'; + copyButton.setAttribute('aria-label', '复制代码'); + copyButton.setAttribute('type', 'button'); + + copyButton.addEventListener('click', () => { + navigator.clipboard.writeText(codeBlock.textContent.trimEnd()).then(() => { + copyButton.textContent = '已复制!'; + copyButton.classList.add('copied'); + + setTimeout(() => { + copyButton.textContent = '复制'; + copyButton.classList.remove('copied'); + }, 2000); + }).catch((err) => { + copyButton.textContent = '失败'; + setTimeout(() => { + copyButton.textContent = '复制'; + }, 2000); + }); + }); + + pre.appendChild(copyButton); + }); +})(); diff --git a/templates/page.html b/templates/page.html index c07d86e..07e91da 100644 --- a/templates/page.html +++ b/templates/page.html @@ -44,3 +44,7 @@ {% endif %} {% endblock content %} +{% block extra_body %} + +{% endblock extra_body %} +