Js implemented native copy text into the clipboard

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:

  1. 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);
  2. Assigned to input content requires assignment
  3. Adding to the document DOM
  4. Select the value (that is, to copy value) input box
  5. Copy command execution
  6. Finally, do not forget to remove elements from a document DOM
  7. 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.

 

Guess you like

Origin www.cnblogs.com/zhaodesheng/p/11464934.html