首先方法一:
<div>
<span id="user_ref_id">复制内容</span>
<input style="margin-left: 30px;" type="button" onclick="cp(document.getElementById('user_ref_id'));" value="复制给好友" >
</div>
function selectText(x) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(x);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(x);
selection.addRange(range);
}
}
function cp(x)
{
selectText(x);
document.execCommand("copy");
alert("复制成功,快去分享好友吧")
}
方法二:
<input type="text" onclick="copy('复制内容')" value="随意" readonly="readonly">
function copy(message) {
var input = document.createElement("input");
input.value = message;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length), document.execCommand('Copy');
document.body.removeChild(input);
alert("复制成功");
}
方法三:
<div class="copy-font">
<div class="uuid-code" id="content">saidfh3is21111h</div>
<button class="btn-copy" id="copyBT">复制</button>
</div>
function copyArticle(event) {
const range = document.createRange();
range.selectNode(document.getElementById('content'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("复制成功!");
}
document.getElementById('copyBT').addEventListener('click', copyArticle, false);
这几个方法都是可以的都可以实现基本的复制功能