首先能做到複製文本的內容
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>