mirror of
https://github.com/Dichgrem/Blog.git
synced 2026-02-04 17:11:57 -05:00
feat:copy_button
This commit is contained in:
32
sass/copy.scss
Normal file
32
sass/copy.scss
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -5,5 +5,6 @@
|
||||
@import 'main';
|
||||
@import 'post';
|
||||
@import 'toc';
|
||||
@import 'copy';
|
||||
@import 'pagination';
|
||||
@import 'footer';
|
||||
|
||||
34
static/copy.js
Normal file
34
static/copy.js
Normal 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);
|
||||
});
|
||||
})();
|
||||
@@ -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 %}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user