feat:copy_button

This commit is contained in:
dichgrem
2026-01-17 12:25:50 +08:00
parent 07d1060183
commit aea50b44ca
5 changed files with 72 additions and 0 deletions

32
sass/copy.scss Normal file
View File

@@ -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;
}

View File

@@ -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;

View File

@@ -5,5 +5,6 @@
@import 'main';
@import 'post';
@import 'toc';
@import 'copy';
@import 'pagination';
@import 'footer';

34
static/copy.js Normal file
View File

@@ -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);
});
})();

View File

@@ -44,3 +44,7 @@
{% endif %}
{% endblock content %}
{% block extra_body %}
<script src="{{ get_url(path='copy.js', trailing_slash=false) | safe }}"></script>
{% endblock extra_body %}