Ghost code black “copy” button
코드블럭을 만들고 publish 를 하면 내용을 쉽게 복사 할 수 없어서 불편하다. 따라서 이번 시간에 버튼을 만들어보자.
목표
코드 블럭 우축 상단에 “Copy” 버튼표시 클릭 時 클립보드로 코드 복사 모든 포스트에 자동 적용
적용방법
자신이 사용하는 테마에 post.hbs or default.hbs 파일을 수정한다.
주의점! post.hbs등 소스코드를 수정하게 되면 기존에 데이터가 꼬일 수 있으니 파일 수정전에 백업을 하는 등 조치를 취하고 진행한다.
필자는 post.hbs
를 사용했다.
<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('pre code').forEach(function (codeBlock) {
const button = document.createElement('button');
button.innerText = 'Copy';
button.className = 'copy-button';
const pre = codeBlock.parentNode;
pre.style.position = 'relative';
button.style.position = 'absolute';
button.style.top = '8px';
button.style.right = '8px';
button.style.padding = '4px 8px';
button.style.fontSize = '12px';
button.style.cursor = 'pointer';
button.style.zIndex = '1';
button.addEventListener('click', function () {
const text = codeBlock.innerText;
navigator.clipboard.writeText(text).then(() => {
button.innerText = 'Copied!';
setTimeout(() => (button.innerText = 'Copy'), 1500);
});
});
pre.appendChild(button);
});
});
</script>
CSS ADD
assets/css/screen.css 에 스타일을 추가한다.
.copy-button {
background: #4f46e5;
color: white;
border: none;
border-radius: 4px;
position: absolute;
top: 8px;
right: 8px;
padding: 4px 8px;
font-size: 12px;
z-index: 10;
cursor: pointer;
}
.copy-button:hover {
background: #4338ca;
}
이후 저장하고 docker ghost를 restart 해준다.
끝.