Fix copy code button position (#1348)

Fix issue #1303 by adding a code wrapper outside the code block. 
Ref:
https://stackoverflow.com/questions/60771472/position-a-button-such-that-it-wont-scroll-with-contents
This commit is contained in:
Yifan Jiang 2023-04-25 15:37:09 +01:00 committed by GitHub
parent 9ef19fa52a
commit 6e38b1b8aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 15 deletions

View File

@ -826,31 +826,23 @@ progress::-moz-progress-bar {
height: inherit;
}
pre {
padding: 8px 12px;
/* Copy button */
.code-display-wrapper {
position: relative;
/* Copy code to clipboard button */
.copy {
background: var(--global-card-bg-color);
border-color: var(--global-bg-color);
border-radius: .3rem;
border-style: solid;
border-style: none;
color: var(--global-text-color);
font-size: medium;
opacity: 0;
position: absolute;
right: .25rem;
top: .25rem;
&:active,
&:focus,
&:hover {
color: var(--global-hover-color);
opacity: 1;
}
right: .15rem;
top: .15rem;
}
&:active .copy,
&:focus .copy,
&:hover .copy {

View File

@ -2,13 +2,13 @@
var codeBlocks = document.querySelectorAll('pre');
codeBlocks.forEach(function (codeBlock) {
if (codeBlock.querySelector('pre:not(.lineno)') || codeBlock.querySelector('code')) {
// create copy button
var copyButton = document.createElement('button');
copyButton.className = 'copy';
copyButton.type = 'button';
copyButton.ariaLabel = 'Copy code to clipboard';
copyButton.innerText = 'Copy';
copyButton.innerHTML = '<i class="fas fa-clipboard"></i>';
codeBlock.append(copyButton);
// get code from code block and copy to clipboard
copyButton.addEventListener('click', function () {
@ -32,5 +32,15 @@ codeBlocks.forEach(function (codeBlock) {
copyButton.innerHTML = '<i class="fas fa-clipboard"></i>';
}, waitFor);
});
// create wrapper div
var wrapper = document.createElement('div');
wrapper.className = 'code-display-wrapper';
// add copy button and code block to wrapper div
const parent = codeBlock.parentElement;
parent.insertBefore(wrapper, codeBlock);
wrapper.append(codeBlock);
wrapper.append(copyButton);
}
});