項目中經常會遇到點擊按鈕復制訂單號、訂單id等內容到粘貼板中的需求。可是通常我們都是用Ctrl + c或右擊復制的,別操心,js也是有復制命令的,那就是document.execCommand('copy'); 這個命令會將選中的內容復制到粘貼板中,那豈不是還需要選中?別急input和textarea元素有一個select()方法,這個方法可以幫我們自動選中。於是就有了下面的代碼,復制過去試試吧!
1
2
3
4
5
6
7
8
9
10
11
|
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),你可以做相應的交互提示等。