使用clipboard.js 实现:
它是一个不需要Flash,就能实现文本复制或者剪切到剪切板的轻量级插件;
具体实例:
可以使用cdn 或者直接下载 设置好引用路径。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>一键复制粘贴功能</title>
<style>
.transfer {
width: 90%;
margin: 20px auto;
font-size: 18px;
}
.transfer button {
margin-top: -5px;
float: right;
margin-left: 10px;
background-color: rgb(3, 169, 244);
width: 30%;
height: 25px;
font-size: 14px;
color: white;
border: 0;
border-radius: 8%;
}
</style>
</head>
<body>
<div class="transfer">
复制:<span id="zfb_account">11111111111</span>
<button onclick="copy1()" data-clipboard-action="copy" data-clipboard-target="#zfb_account" id="copy_zfb">一键复制</button>
</div>
<div class="transfer">
复制粘贴:<span id="wx_account">2222222</span>
<button onclick="copy2()" data-clipboard-action="copy" data-clipboard-target="#wx_account" id="copy_wx">一键复制粘贴</button>
</div>
<input type="text" id="text"/>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js"></script>
<script>
function copy1() {
var clipboard = new Clipboard('#copy_zfb');
clipboard.on('success', function(e) {
alert("复制成功!"+e.text);
e.clearSelection(); //选中需要复制的内容
});
clipboard.on('error', function(e) {
alert("当前浏览器不支持此功能,请手动复制。")
});
}
function copy2() {
var clipboard = new Clipboard('#copy_wx');
clipboard.on('success', function(e) {
e.clearSelection(); //选中需要复制的内容
document.getElementById("text").value=e.text
alert("复制成功!");
});
clipboard.on('error', function(e) {
alert("当前浏览器不支持此功能,请手动复制。")
});
}
</script>
</html>