开发中经常会用到复制的功能,在 IE 下实现比较简单。但要想做到跨浏览器比较困难了。本文将介绍一个跨浏览器的库类 Zero Clipboard 。它利用 Flash 进行复制,所以只要浏览器装有 Flash 就可以运行,而且比 IE 的 document.execCommand("Copy") 更加灵活。
Zero Clipboard 的实现原理
Zero Clipboard 利用 Flash 进行复制,之前有 Clipboard Copy 解决方案,其利用的是一个隐藏的 Flash。但最新的 Flash Player 10 只允许在 Flash 上进行操作才能启动剪贴板。所以 Zero Clipboard 对此进行了改进,用了一个透明的 Flash ,让其漂浮在按钮之上,这样其实点击的不是按钮而是 Flash ,也就可以使用 Flash 的复制功能了。
如何使用 Zero Clipboard
首先下载 Zero Clipboard ,并解压缩。其中需要两个文件:ZeroClipboard.js 和 ZeroClipboard.swf ,将这两个文件放入到你的项目中。
下载地址:http://zeroclipboard.org/
演示地址:http://demo.jb51.net/js/ZeroClipboard/index.html
废话不多说了,开始!!!
第一步,导入 ZeroClipboard.js 、ZeroClipboard.swf文件
<script type="text/javascript" src="ZeroClipboard.js"></script>
再设置 ZeroClipboard.swf 文件的路径。moviePath: 'js/ZeroClipboard.swf', // URL to movie
ZeroClipboard.js源代码
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard = {
version: "1.0.7",
clients: {}, // registered upload clients on page, indexed by id
moviePath: 'ZeroClipboard.swf', // URL to movie 这里设置ZeroClipboard.swf路径
nextId: 1, // ID of next movie
$: function(thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function() { this.style.display = 'none'; };
thingy.show = function() { this.style.display = ''; };
thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
thingy.removeClass = function(name) {
var classes = this.className.split(/\s+/);
var idx = -1;
for (var k = 0; k < classes.length; k++) {
if (classes[k] == name) { idx = k; k = classes.length; }
}
if (idx > -1) {
classes.splice( idx, 1 );
this.className = classes.join(' ');
}
return this;
};
thingy.hasClass = function(name) {
return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
};
}
return thingy;
},
setMoviePath: function(path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function(id, e