Jekyll博客添加代码框一键复制按钮与复制提示

 
Category: Frontend

写在前面

之前一直想试试代码一键复制, 但是看了很多博客都是大改主题, 自己并没有系统学过前端的东西, 只能求助于 AGI 了.

结果发现 chatGPT3.5 免费版还是厉害, Gemini 虽然上了 Pro 还是差点意思

我的博客在这里: zorchp.github.io

js 逻辑

assets/js/copy-to-clipboard.js

document.addEventListener('DOMContentLoaded', function () {
	var codeBlocks = document.getElementsByTagName('code');

	for (var i = 0; i < codeBlocks.length; i++) {
		var codeBlock = codeBlocks[i];

		var button = document.createElement('button');
		button.textContent = 'Copy';
		button.classList.add('copy-button'); // add CSS class
		codeBlock.parentNode.insertBefore(button, codeBlock.nextSibling);

		var clipboard = new ClipboardJS(button, {
			target: function (trigger) {
				return trigger.previousSibling;
			}
		});
		clipboard.on('success', function (e) {
			e.clearSelection();
			var notification = document.createElement('div');
			notification.textContent = 'Copied!';
			notification.classList.add('notification');
			document.body.appendChild(notification);
			setTimeout(function () {
				notification.style.opacity = '0';
				setTimeout(function () {
					document.body.removeChild(notification);
				}, 1000);
			}, 1000);
			// console.log('已复制到剪贴板:', e.text);
		});
		clipboard.on('error', function (e) {
			console.error('复制失败:', e.action);
		});
	}
});

主要是使用 clipboard.js 来实现. 遍历找 code 标签页. 我加了复制成功的渐隐效果.

CSS

assets/css/copy.css

div.highlight {
	position: relative;
}

div.highlight .copy-button {
	position: absolute;
	top: 0px;
	right: 0px;
	border: .3px solid orange;
	border-radius: 1px;
}

.notification {
	position: fixed;
	top: 0;
	left: 50%;
	transform: translateX(-50%);
	padding: 10px;
	color: antiquewhite;
	opacity: 1;
	transition: opacity 1s;
}

html

_includes/head/custom.html

<!-- copy to clipboard -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script src="/assets/js/copy-to-clipboard.js"></script>
<link rel="stylesheet" type="text/css" href="/assets/css/copy.css" />

把主要逻辑放进 head 的自定义 html 中, 就可以了.