If you want to copy content to the clipboard through js, it is not difficult, but if you consider the compatibility of the browser, it becomes a bit troublesome. Using jquery-zclip copy is a good choice. Use flash to achieve browser compatibility. . I won’t explain the principle in detail, let’s talk about how to implement it.
For example, my html code is as follows:
The code copy is as follows:
<div>
<code rel="1"><span id="id_1">Content to be copied1</span></code>
<code rel="2"><span id="id_2">Content to be copied 2</span></code>
<code rel="3"><span id="id_3">Content to be copied3</span></code>
</div>
There are two js files in total, so there is no need to mention jquery, and then jquery-zclip.js and ZeroClipboard.swf. These two files can be downloaded on the official website, and the address is as follows: http://www.steamdev.com/zclip /
The js that generates the copy button are as follows
The code copy is as follows:
<script type="text/javascript">
$(function(){
$('code').each(function(){
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
'afterCopy':function(){
alert('get the address of the corresponding code has been copied to the clipboard, you can use ctrl+v to paste');
},
'copy':function(){
return $('#id_'+id).text();//Note here, if div span, etc. use text(), if input, use val(), this support is not very good
}
});
});
});
</script>
This way, you can copy time across browsers. It was not a difficult thing. I did a test smoothly. But when I put it in the project, there was a problem. There was no flash in the copy button generated, only Text, I later found that flash was actually generated, but it was not in the location of the text. It probably has something to do with the iframe structure used in the background of my project. I guess this is a bug in this plugin. Later, I checked a lot of information, and some people Said that you need to change the code, but then I changed it and it was OK
The code that needs to be modified is as follows
The code copy 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 modification
//info.top += obj.offsetTop; //Before modification
jpos = $(obj).position(); //After modifying
info.left += jpos.left; //After modification
info.top += jpos.top; //After modification
}
return info;
}
In fact, this has something to do with the principle of this plugin, so it covers a transparent flash on the button. If the two of them do not overlap, the above problem will occur.