項目中經常會遇到點擊按鈕復制訂單號、訂單id等內容到粘貼板中的需求。可是通常我們都是用Ctrl + c或右擊復制的,別操心,js也是有復制命令的,那就是document.execCommand('copy'); 這個命令會將選中的內容復制到粘貼板中,那豈不是還需要選中?別急input和textarea元素有一個select()方法,這個方法可以幫我們自動選中。於是就有了下面的代碼,復制過去試試吧!
function copy(text) {
var input = document.createElement('input');
input.setAttribute('readonly', 'readonly'); // 防止手機上彈出軟鍵盤
input.setAttribute('value', text);
document.body.appendChild(input);
// input.setSelectionRange(0, 9999);
input.select();
var res = document.execCommand('copy');
document.body.removeChild(input);
return res;
}
思路分析:
- 創建input或textarea,因為這兩個DOM具有select方法,可以選中內容(document.execCommand('copy')復制內容必要條件);
- 給input賦值為需要賦值的內容
- 將DOM添加到文檔中
- 選中輸入框中的值(也就是要復制的值)
- 執行復制命令
- 最后別忘了從文檔中移除DOM元素
- 此函數最后返回了復制是否成功的結果(true/false,document.execCommand('copy')本身會返回true/false),你可以做相應的交互提示等。
后面實踐發現,當要復制的內容中含有tab符號或者換行的符號時,復制的結果就不是想要的結果了,因為input不支持換行,然后textarea是支持的,所以,對這個函數修改了一下,下面這個目前使用起來還沒遇到問題,有問題的小伙伴歡迎留言評論
/**
* @auth zhaodesheng
* @param {String} text 需要復制的內容
* @return {Boolean} 復制成功:true或者復制失敗:false 執行完函數后,按ctrl + v試試
*/
function copy(text) {
var textareaEl = document.createElement('textarea');
textareaEl.setAttribute('readonly', 'readonly'); // 防止手機上彈出軟鍵盤
textareaEl.value = text;
document.body.appendChild(textareaEl);
textareaEl.select();
var res = document.execCommand('copy');
document.body.removeChild(textareaEl);
console.log("復制成功");
return res;
}
