Copy content to clipboard compatible browsers using js

  • 2020-03-30 02:22:04
  • OfStack

If you want to use js to copy content to the clipboard, it is not difficult, but if you consider the browser compatibility problems, it becomes a bit troublesome, using jquery-zclip copy is a good choice, with flash to achieve browser compatibility. I won't go into the details of the principle, but let's talk about how to implement it.

For example, my HTML code is as follows:
<div class="buttonBox"> 
<code rel="1"><span id="id_1"> The content to be copied 1</span></code> 
<code rel="2"><span id="id_2"> The content to be copied 2</span></code> 
<code rel="3"><span id="id_3"> The content to be copied 3</span></code> 

Js file, it will be altogether two, jquery is needless to say, and jquery - zclip. Js and ZeroClipboard SWF, these two files can be downloaded in the website, the address is as follows:

Generate the js for the copy button as follows
<script type="text/javascript"> 
var self = $(this); 
var id = self.attr('rel'); 
var copy = $('<span> copy </span>').appendTo(self).zclip({ 
'path':'/static/admin/js/ZeroClipboard.swf',//Write your own address here
alert(' Gets the address of the corresponding code that has been copied to the clipboard , You can use ctrl+v paste '); 
return $('#id_'+id).text();//Notice that if div span and so on use text(), and if input and so on use val(), this doesn't support very well


So you can time cross-browser replication, originally is not a difficult thing, when I do the test also pretty smoothly, can when I put him in the project is a problem, copy button position without flash, only words, later found that actually flash generated, but not in text location, estimated project background and I use the iframe structure, estimates that this is a bug of the plug-in, then check a lot of information, some people say, need to change the code is ok, then I changed,, indeed as expected

The code to be modified is as follows
getDOMObjectPosition: function (obj, stopObj) { 
// get absolute coordinates for dom element 
var info = { 
left: 0, 
top: 0, 
width: obj.width ? obj.width : obj.offsetWidth, 
height: obj.height ? obj.height : obj.offsetHeight 

if (obj && (obj != stopObj)) { 
//info.left += obj.offsetLeft; // Before the change  
// += obj.offsetTop; // Before the change  
jpos = $(obj).position(); //The modified
info.left += jpos.left; //The modified +=; //The modified

return info; 

Actually this has to do with the principle of this plug-in, it will be a transparent flash to cover the top of the button, if they do not coincide, the above problem.

Related articles: