js实现复制内容到粘贴板

时间:2023-03-08 23:48:35
js实现复制内容到粘贴板
 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js复制内容到粘贴板</title>
<style>
.flex-r {
display: flex;
flex-direction: row;
align-content: center;
justify-content: space-between;
}
.info {
max-width: 400px;;
margin-bottom: 20px;
background-color: bisque;
}
dl {
margin: 0;
padding: 0 30px;
width: 200px;
}
.copy{
cursor: pointer;
margin: 0 10px;
}
</style>
</head> <body>
<div class="bank_info">
<div class="flex-r info">
<dl class="flex-r aln-star">
<dt>收款银行:</dt>
<dd>建设银行</dd>
</dl>
<span class="copy" onclick="mmcopy(this)">复制</span>
</div>
<div class="flex-r info">
<dl class="flex-r aln-start">
<dt>收款账户名:</dt>
<dd>张三</dd>
</dl>
<span class="copy" onclick="mmcopy(this)">复制</span>
</div>
</div> <!--引入jQuery插件 -->
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<script>
function mmcopy(e) {
if (document.execCommand("copy")) {
var txt = ""; // 需要复制的文字
txt += $(e)
.siblings("dl")
.find("dt")
.text();
txt += $(e)
.siblings("dl")
.find("dd")
.text();
const input = document.createElement("input"); // 创建一个新input标签
input.setAttribute("readonly", "readonly"); // 设置input标签只读属性
input.setAttribute("value", txt); // 设置input value值为需要复制的内容
document.body.appendChild(input); // 添加input标签到页面
input.select(); // 选中input内容
input.setSelectionRange(0, 9999); // 设置选中input内容范围
document.execCommand("copy"); // 复制
document.body.removeChild(input); // 删除新创建的input标签
}
}
</script>
</body>
</html>