最近遇到一個需求,需要點選按鈕,複制 <p> 标簽中的文本到剪切闆
之前做過複制輸入框的内容,原以為差不多,結果發現根本行不通
嘗試了各種辦法,最後使了個障眼法,實作了下面的效果

一、原理分析
浏覽器提供了 copy 指令 ,可以複制選中的内容
document.execCommand("copy")
如果是輸入框,可以通過 select() 方法,選中輸入框的文本,然後調用 copy 指令,将文本複制到剪切闆
但是 select() 方法隻對 <input> 和 <textarea> 有效,對于 <p> 就不好使
最後我的解決方案是,在頁面中添加一個 <textarea>,然後把它隐藏掉
點選按鈕的時候,先把 <textarea> 的 value 改為 <p> 的 innerText,然後複制 <textarea> 中的内容
二、代碼實作
HTML 部分
<style type="text/css">
.wrapper {position: relative;}
#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}
</style>
<div class="wrapper">
<p id="text">我把你當兄弟你卻想着複制我?</p>
<textarea id="input">這是幕後黑手</textarea>
<button onclick="copyText()">copy</button>
</div>
JS 部分
<script type="text/javascript">
function copyText() {
var text = document.getElementById("text").innerText;
var input = document.getElementById("input");
input.value = text; // 修改文本框的内容
input.select(); // 選中文本
document.execCommand("copy"); // 執行浏覽器複制指令
alert("複制成功");
}
</script>
親測,Firefox 48.0,Chrome 60.0,IE 8 都能用
三、一鍵複制
分享一個自己工作中用到的一鍵複制方法
/**
* 一鍵粘貼
* @param {String} id [需要粘貼的内容]
* @param {String} attr [需要 copy 的屬性,預設是 innerText,主要用途例如指派 a 标簽上的 href 連結]
*
* range + selection
*
* 1.建立一個 range
* 2.把内容放入 range
* 3.把 range 放入 selection
*
* 注意:參數 attr 不能是自定義屬性
* 注意:對于 user-select: none 的元素無效
* 注意:當 id 為 false 且 attr 不會空,會直接複制 attr 的内容
*/
copy (id, attr) {
let target = null;
if (attr) {
target = document.createElement('div');
target.id = 'tempTarget';
target.style.opacity = '0';
if (id) {
let curNode = document.querySelector('#' + id);
target.innerText = curNode[attr];
} else {
target.innerText = attr;
}
document.body.appendChild(target);
} else {
target = document.querySelector('#' + id);
}
try {
let range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
console.log('複制成功')
} catch (e) {
console.log('複制失敗')
}
if (attr) {
// remove temp target
target.parentElement.removeChild(target);
}
}