博客园如何自定义添加复制按钮?
//添加复制按钮
这是js部分
<script> let cnblogs_code = document.querySelectorAll('.cnblogs_code') for(let i=0;i<cnblogs_code.length;i++){
let copy_li = document.createElement('div')
//因为我添加了一个类名,所以下面的js添加样式可以加到.copy.btn类里,我懒的改 copy_li.classList.add('copy_btn'); copy_li.style.position = 'absolute'; copy_li.style.right = '10px' copy_li.style.top = '10px' copy_li.style.textAlign = 'center' copy_li.innerText = '复制' copy_li.style.padding = '0px 10px'; copy_li.style.height = '24px'; copy_li.style.lineHeight = '26px'; copy_li.style.cursor = 'pointer' cnblogs_code[i].appendChild(copy_li) copy_li.addEventListener("click",()=>{ let p = cnblogs_code[i].querySelector('pre')
//获取标签里的文本内容 let textValue =p.innerText
//创建input标签元素 let inputV = document.createElement('input')
//给input框赋值 inputV.value = textValue
//将input添加到body标签里 document.body.appendChild(inputV);
//选中文本内容 inputV.select();
//复制 let result = document.execCommand('Copy'); if(result){ copy_li.innerText = '复制成功' }
//删除input标签 inputV.remove() }) }
</script>
//这是css部分
<style>
.cnblogs_code{
position: relative;
}
.copy_btn{
font-size: 16px;
box-shadow: 0 2px 4px rgb(0 0 0 / 5%), 0 2px 4px rgb(0 0 0 / 5%);
color: #fffefe;
#cbb8b8 !important;
border-radius: 4px;
}
</style>
复制
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?