js的复制功能,兼容安卓和ios,亲测有效
Android
安卓系统的就比较随意一点。
<script>
var input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value', '我是复制的内容');
document.body.appendChild(input);
input.setSelectionRange(0, 9999);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}
document.body.removeChild(input);
</script>
IOS系统
IOS的用法与Android有些不同,因为IOS上识别复制得是不能被覆盖的文本节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复制到剪切板效果</title>
</head>
<body>
<div id="copyBT">这是要复制的1内容</div>
<a id="contentas">这是复制按钮</a>
<script>
function copyArticle(event) {
const range = document.createRange();
range.selectNode(document.getElementById('copyBT'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("复制成功")
}
document.getElementById('contentas').addEventListener('click', copyArticle, false);
</script>
</body>
</html>
兼容写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复制到剪切板效果</title>
</head>
<body>
<div id="copyBT">这是要复制的1内容</div>
<a id="contentas">这是复制按钮</a>
<script>
function copyArticle(event) {
if(navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)){
const range = document.createRange();
range.selectNode(document.getElementById('copyBT'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("复制成功")
}else{
var input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value','我是复制的内容');
document.body.appendChild(input);
input.setSelectionRange(0, 9999);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}
document.body.removeChild(input);
}
}
document.getElementById('contentas').addEventListener('click', copyArticle, false);
</script>
</body>
</html>
看懂之后,根据自己需要再去修整复制什么的数据就好了。