Projects often encounter click the button to copy the order number, order id and other content to the clipboard in demand. But generally we are using Ctrl + c or right-click to copy, do not worry, js is also a copy command, and that is document.execCommand ( 'copy'); copy of this order will be selected content to the clipboard, then You not also need to check? Do not worry input and textarea elements have a select () method, which can help us automatically selected. Then there is the following code, copy past try it!
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; }
Analysis of ideas:
- Create input or TextArea, because both have a select DOM methods, can select the contents (document.execCommand ( 'copy') copy the contents of a necessary condition);
- Assigned to input content requires assignment
- Adding to the document DOM
- Select the value (that is, to copy value) input box
- Copy command execution
- Finally, do not forget to remove elements from a document DOM
- This function returns whether the last copy successful results (true / false, document.execCommand ( 'copy') itself returns true / false), you can do the appropriate interaction prompts.