hexo-theme-snippet
hexo-theme-snippet copied to clipboard
希望添加复制代码功能
Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
Describe the solution you'd like A clear and concise description of what you want to happen.
Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.
Additional context Add any other context or screenshots about the feature request here.
建议已收到,谢谢
在head.ejs中添加如下代码 js代码
<script type="text/javascript">
function copyToClip(event) {
let cb = event.target.parentNode;
var cls = cb.getElementsByClassName("line");
var pt = ""
for (var k = 0; k < cls.length; k++) {
var cl = (cls[k].textContent || cls[k].innerHTML);
cl = cl.replace('<span class="css"></span>', "\n")
cl = cl.replace('<span class="javascript"></span>', "\n")
pt += cl
pt += "\n";
}
const textarea = document.createElement('textarea');
textarea.value = pt;
document.body.appendChild(textarea);
textarea.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
}
document.body.removeChild(textarea);
alert("复制成功");
}
function doAddCopyCode() {
var codeBlocks = document.getElementsByClassName('code');
for (var i = 0; i < codeBlocks.length; i++) {
//创建一个div
var divCopy = document.createElement("div");
divCopy.innerHTML = "点击复制"
//为div创建属性class = "test"
var divattr = document.createAttribute("class");
divattr.value = "copy_my_code";
//把属性class = "test"添加到div
divCopy.setAttributeNode(divattr);
codeBlocks[i].appendChild(divCopy)
var code = codeBlocks[i].getElementsByTagName("pre")[1];
codeBlocks[i].onclick = (e) => {
copyToClip(e);
}
}
}
window.addEventListener('load', function () {
doAddCopyCode();
}, false);
</script>
样式添加
<style type="text/css">
.copy_my_code {
position: absolute;
top: 0;
right: 0;
border: 1px solid;
background: #555;
color: #fff;
margin: 1px;
padding: 0px 5px;
cursor: pointer;
}
</style>