zl程序教程

您现在的位置是:首页 >  前端

当前栏目

【教程】HTML用Jquery为pre标签代码块增加复制代码功能

jQuery教程HTML代码 功能 复制 标签 增加
2023-06-13 09:15:24 时间

代码主要参考自这篇:为网站代码块pre标签增加一个复制代码按钮代码_普通网友的博客-CSDN博客_pre js

但由于博客内未提供完整代码,并且我自己用起来有点小问题,所以这里修改后提供了完整版。

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>demo</title>

		<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
		<style>
	        .content{
	            width: 1000px;
	            margin: 10px auto;
	        }
	        .content pre{
	            position: relative;
	            background-color: #f5f5f5;
	            border: 1px solid #ccc;
	            border-radius: 4px;
	            padding: 10px;
	        }
	        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;
	        }
	        textarea{
	            width: 100%;
	        }
		</style>
	</head>

	<body>
		<div class="content">
			<pre>
				NSArray *levelBinTemplates = rackLevel.binTemplates;
				float maxBinHeight = 0;
				for (WMBinTemplate2 *binTemplate in levelBinTemplates)
				{
				    float binHeight = binTemplate.height * ratioH;
				    if (binHeight > maxBinHeight) {
				        maxBinHeight = binHeight;
				    }
				}
			</pre>
			<pre>
				123
			</pre>
		</div>
		
		<script>
			$(function(){
			    //给每一串代码元素增加复制代码节点
			    let preList = $(".content pre");
			    // for (let pre of preList) {
			    //     //给每个代码块增加上“复制代码”按钮
			    //     let btn = $("<span class=\"btn-pre-copy\" onclick='preCopy(this)'>复制代码</span>");
			    //     btn.prependTo(pre);
			    // }
				preList.each(function(){
					let btn = $("<span class=\"btn-pre-copy\" onclick='preCopy(this)'>复制代码</span>");
			        btn.prependTo($(this));
				});
			});
	 
			/**
		    * 执行复制代码操作
		    * @param obj
		    */
			function preCopy(obj) {
			    //执行复制
			    let btn = $(obj);
			    let pre = btn.parent();
			    //为了实现复制功能。新增一个临时的textarea节点。使用他来复制内容
			    let temp = $("<textarea></textarea>");
			    //避免复制内容时把按钮文字也复制进去。先临时置空
			    btn.text("");
			    temp.text(pre.text());
			    temp.appendTo(pre);
			    temp.select();
			    document.execCommand("Copy");
			    temp.remove();
			    //修改按钮名
			    btn.text("复制成功");
			    //一定时间后吧按钮名改回来
			    setTimeout(()=> {
			        btn.text("复制代码");
			    },1500);
			}
		</script>
	</body>
</html>