复制文本到剪切板

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>复制文本到剪切板</title>
</head>

<body>
<div class="aini">爱你一辈子</div>
<button>点击</button>

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>

<script>
function copyToClipboard(text) {
if (text.indexOf('-') !== -1) {
let arr = text.split('-');
text = arr[0] + arr[1];
}
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = '0';
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? '成功复制到剪贴板' : '该浏览器不支持点击复制到剪贴板';
alert(msg);
} catch (err) {
alert('该浏览器不支持点击复制到剪贴板');
}

document.body.removeChild(textArea);
}


$('button').click(function() {
// console.log($('.aini'));
console.log($('.aini').text());
copyToClipboard($('.san_shang').text());
});
</script>

</body>

</html>
posted @ 2018-09-04 17:34  小猴子会上树  阅读(318)  评论(0编辑  收藏  举报