Demand Scenarios
Using the Document.execcommand () method, the following abbreviation is "Command API".
Example one HTML section
<input type="text" id="text_input"/><button type="button" id="copy_text">copy</button>
JavaScript section
varInputelem= Document.getElementById(' Text_input ');varBtnelem= Document.getElementById(' Copy_text ');Btnelem.AddEventListener(' click ', function(){ if(!Document.execcommand){ Console.Error(' Copy unsupport '); return; } Inputelem.Select(); varResult= Document.execcommand(' Copy '); if(Result){ Console.Log(' Copy Success '); } Else { Console.Error(' Copy fail '); }});
Example Two
In actual development, the content that needs to be copied is usually the text in the text element. At this point, you can use a table cell that is not in the visible region to be implemented.
HTML section
<input type="text" id="text_input" /><p>paragraph</p><button type="button" id="copy_text">copy</button>
CSS Section
#text_input{ position:absolute; top:-100px;}
JavaScript section
varInputelem= Document.getElementById(' Text_input ');varBtnelem= Document.getElementById(' Copy_text ');varTextelem= Document.Queryselector(' P ');Btnelem.AddEventListener(' click ', function(){ if(!Document.execcommand){ Console.Error(' current environment does not support replication feature '); return; } Inputelem.value = Textelem.InnerText; Inputelem.Select(); varResult= Document.execcommand(' Copy '); if(Result){ Console.Log(' Copy Success '); } Else { Console.Error(' Copy fail '); }});
The difference from example one is that you need to assign a value to a FORM element before it is selected.
Precautions
- This step is necessary to detect whether the current environment supports the command API.
- The browser environment does not support the command API and requires a reasonable prompt for the user to manually copy the operation. Therefore, the text element must not be set so that
user-select: none; the text cannot be selected.
- The form element must be in the selected state, that is, the method is called
inputElement.select() , and the text element has no select() method.
- It is not possible
display: none; to use or visibility: hidden; hide form elements after testing. Therefore, this form element can only be positioned outside the area where it is visible.
More Solutions
- Clipboard.js: A plugin that does not rely on flash. The implementation principle is similar to the example above, and the use of plugins can simplify a lot of development work.
Mobile implementation copy content to clipboard