html代码块文本复制
以下js代码可以让你通过仅添加<scipt>
标签就实现在任意一个支持js注入的博客平台上轻松地实现复制该代码块(包括samp
,code
,pre
元素)内的代码文本,实现原理:clipboard api
window.addEventListener('DOMContentLoaded', function() {
const selectors = ['pre', 'samp', 'code'];
selectors.forEach(sel => {
document.querySelectorAll(sel).forEach(el => {
const btn = document.createElement('button');
btn.innerHTML = '⎘';
btn.style.position = 'absolute';
btn.style.top = '1rem';
btn.style.right = '1rem';
btn.style.border = '1px solid #ddd';
btn.style.backgroundColor = '1px solid #ccc';
btn.style.borderRadius = '20%';
btn.style.color = 'inherit';
btn.style.zIndex = '10';
if (getComputedStyle(el).position === 'static') {
el.style.position = 'relative';
}
btn.onclick = function(e) {
e.stopPropagation();navigator.clipboard.writeText(el.innerText);
btn.innerHTML = '✓'; setTimeout(()=>btn.innerHTML = '⎘', 500);
};
el.appendChild(btn);
});
});
});
- 本文标题:html代码块文本复制
- 本文作者:uygnil
- 本文链接:https://blog.zhoulingyu.net/index.php/archives/12/
- 版权声明:本文采用 CC BY 4.0 协议进行许可
标签:无