Write the reason for this function needless to say, it must be: there is demand, but there is no available code on the Internet, no way, in order to mix the rice to eat you have to write to realize the demand! (I first write a blog, technical slag, in order to improve the level, came to water Bo Park, the heart of the joy! )
In order to achieve this demand, read a lot of blog, find a lot of information, but many are using window.clipboardData.setData () and so on, and now the browser does not seem to support this property! (at least Chrom and Firefox are not working!) ), the other is very messy, not encapsulated into a method; so I encapsulated a good copy method for the convenience of later use: CopyText (compatible with Chrom and firefox,ie not tested);
1 functionCopyText (ele) {2 functionOtherele (Element) {3 if(document.selection) {4 varRange =Document.body.createTextRange ();5 Range.movetoelementtext (element);6 Range.Select ();7}Else{8 window.getselection (). Removeallranges ();9 varRange =Document.createrange ();Ten Range.selectnode (element); One window.getselection (). AddRange (range); A } - } - if(ele.select) { the Ele.select (); -}Else{ - Otherele (ele); - } +Document.execcommand (' Copy '); - window.getselection (). Removeallranges (); +}
The method needs to pass in a parameter, which is the DOM element for which you want to copy the content, no matter what type you can!
The first time you write a blog, feel useful to give some encouragement!
JavaScript Click button to copy specified content function