版权声明:本文为博主原创文章,转载请注明出处!!!(●◡●) https://blog.csdn.net/Small_Mouse0/article/details/89398672
首先能做到复制文本的内容
js提供原生命令【document.execCommand(“copy”);】便可以复制用户选择的内容,做个测试
document.execCommand("copy");
自动选择,并复制文本的内容
输入框可做自动选择,,通过输入框自动选择然后选择文本
var input = document.getElementById("text");
input.select(); // 选中文本
document.execCommand("copy"); // 执行浏览器复制命令
alert("复制成功");
如何隐藏输入框?
使用【display: none】【hidden】?这样会隐藏输入框,会造成无法选中。
变相的做法是把输入框显示在用户看不到的地方,可以是显示在屏幕外,或者用别的元素挡住。
参考代码完整
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#text {
position: absolute;
top: -100px;
}
</style>
</head>
<body>
<div class="wrapper">
<input type="text" id="text" value="你居然敢复制我!!" style="width: 300px;" >
<button onclick="copyText()">复制</button>
</div>
</body>
<script type="text/javascript">
function copyText() {
text = 'aa';
var input = document.getElementById("text");
input.select(); // 选中文本
document.execCommand("copy"); // 执行浏览器复制命令
alert("复制成功");
}
</script>
</html>