2024年07月27日 建站教程
1、给每一串代码元素增加复制代码节点JS代码
$(function(){ let preList = $(".show pre"); for (let pre of preList) { //给每个代码块增加上“复制代码”按钮 let btn = $("复制代码"); btn.prependTo(pre); } }); /*执行复制代码操作*/ function preCopy(obj) { //执行复制 let btn = $(obj); let pre = btn.parent(); //为了实现复制功能。新增一个临时的textarea节点。使用他来复制内容 let temp = $("<textarea></textarea>"); //避免复制内容时把按钮文字也复制进去。先临时置空 btn.text(""); temp.text(pre.text() + '原文链接:' + window.location.href); //复制后戴上本站的链接 temp.appendTo(pre); temp.select(); document.execCommand("Copy"); temp.remove(); btn.text("复制成功"); setTimeout(()=> { btn.text("复制代码"); },1500); }
2、CSS样式
.show pre { position: relative; font-family: Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; word-wrap: normal; word-break: break-all; white-space: pre; overflow-x: scroll; overscroll-behavior-x: contain; margin-top: 10px; margin-bottom: 0; border-radius: 4px; z-index: 0; padding: 1em; line-height: 1.5; color: #ccc; background: #2d2d2d; font-size: 14px; padding-left: 50px; } .show pre .btn-pre-copy{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -khtml-user-select: none; user-select: none; position: absolute; top: 10px; right: 12px; font-size: 12px; line-height: 1; cursor: pointer; color: hsla(0,0%,54.9%,.8); transition: color .1s; } .show pre .btn-pre-copy:hover{ color: #fff; }
3、如何不想用插件,要显示pre的行数1,2,3,4,5
let preList = $(".show pre"); let ulList = [] for(let i=0; i<preList.length; i++){ let ul = '' //给每个代码块增加上“复制代码”按钮 let preNum = preList.eq(i).html().split(/\n/).length ul += '<ul>' for(let j=1; j<preNum; j++){ ul += '<li>' + (j) + '</li>' } ul += '</ul>' ulList.push(ul) } for(let i=0; i<preList.length; i++){ for(let j=0; j<ulList.length; j++){ if(i == j){ preList.eq(i).append(ulList[j]) } } }
4、CSS样式
.show pre ul{ position: absolute; left: 0; top: 0; background: #464541; padding: 1em 10px; line-height: 1.5; }
本文链接:http://so.lmcjl.com/news/9269/