clipboardjs 自动复制.js如何不通过点击事件来实现复制功能

没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!如何用JS在浏览器中实现复制功能? - 知乎47被浏览<strong class="NumberBoard-itemValue" title="分享邀请回答387 条评论分享收藏感谢收起0添加评论分享收藏感谢收起写回答在ie中window.clipboardData(剪切板对象)是可以被获取,所以利用这个方法我们可以实现在IE当中复制粘贴的功能,demo如下!
&meta http-equiv="Content-Type" content="text/ charset=utf-8"&
&title&clipboard&/title&
&SCRIPT language=JavaScript&
function copy()
var obj=document.getElementById("txarea");
window.clipboardData.setData("Text",obj.value);//设置数据
alert("复制成功");
function paste() {
var obj=document.getElementById("txarea");
var clipboard = window.clipboardData.getData('Text');
clipboard == null ? alert('no data') : obj.value =
&INPUT name=Button onClick="txarea.value=''" type=button value='clear'&
&INPUT name=Button onClick="copy('textarea')" type=button value='copy'&
&INPUT name=Button onClick="paste('textarea')"; type=button value='paste'&&br&
&textarea name="txarea" id="txarea" cols="105" rows="11" class="transform"&&/textarea&&/p&
上述代码在IE中访问是可以实现复制粘贴的!但是其他浏览器并不被支持!于是找了下资料,由于现在浏览器种类也越来越多,诸如 IE、Firefox、Chrome、Safari等等,因此现在要实现一个js复制内容到剪贴板的小功能就不是一件那么容易的事了。 在FLASH 9 时代,有一个通杀所有浏览器的js复制内容到剪贴板的方案:这个方案是一个最流行的方法: 著名的Clipboard Copy解决方案 利用一个clipboard.swf作为桥梁,复制内容到剪贴板。原理是:创建一个隐藏的flash文件,同时给给flash的变量FlashVars 赋&clipboard=..&,通过这个赋值flash就会把复制的内容放到剪贴板。这个方法兼容IE、Firefox、Opera、chrome、 Safari,真可谓&万能&的解决方案。浏览器Flash的安装率非常高,这几乎是一个完美的解决方案。
demo如下所示:
&!DOCTYPE HTML&
&html lang="en"&
&meta charset="utf-8"/&
&meta name="copyright" content=""/&
&title&复制粘贴&/title&
&div class="one"&
&input type="text" class="gift_num fl" value="XXXXXXXXXXXXXXXXXXXXXX" disabled="disabled" readonly="true"/&
&a href="javascript:;" hidefocus="none" class="btn_copy block fl" id="btnCopy"&复制&/a&
&script type="text/javascript" src="jquery.min.js"&&/script&
&script type="text/javascript" src="ZeroClipboard.js"&&/script&
&script type="text/javascript"&//这里的参数说明一下,text是要复制的文本内容,button是点击触发复制的dom对象,msg是复制成功后的提示信息,parent是包含flash的父元素
function clipboard(text, button, msg, parent) {
if (window.clipboardData) {//如果是IE浏览器
var copyBtn = document.getElementById(button);
copyBtn.onclick = function() {
window.clipboardData.setData('text', text);
alert(msg);
} else {//非IE浏览器
var clip = new ZeroClipboard.Client();//初始化一个剪切板对象
clip.setHandCursor(true);//设置手型游标
clip.setText(text);//设置待复制的文本内容
clip.addEventListener("mouseUp", function(client) {//绑定mouseUp事件触发复制
alert(msg);
clip.glue(button,parent);//调用ZeroClipboard.js的内置方法处理flash的位置的问题
return false;
$(function(){
clipboard($(".gift_num").val(),"btnCopy","复制成功",'btnCopy');//调用方式
针对上面的demo,我修改了下ZeroClipboard.js插件里面的代码,以便能在不确定复制按钮在什么位置的情况下可以使用!代码如下:红色是修改过的代码
var ZeroClipboard = {
version: "1.0.7",
clients: {},
moviePath: '/js/ZeroClipboard.swf',
nextId: 1,
$: function(thingy) {
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
thingy.hide = function() {
this.style.display = 'none';
thingy.show = function() {
this.style.display = '';
thingy.addClass = function(name) {
this.removeClass(name);
this.className += ' ' +
thingy.removeClass = function(name) {
var classes = this.className.split(/\s+/);
var idx = -1;
for (var k = 0; k & classes. k++) {
if (classes[k] == name) {
k = classes.
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*"));
setMoviePath: function(path) {
this.moviePath =
dispatch: function(id, eventName, args) {
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
register: function(id, client) {
this.clients[id] =
getDOMObjectPosition: function(obj, stopObj) {
var info = {
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
while (obj && (obj != stopObj)) {
info.left += obj.offsetL
info.top += obj.offsetT
obj = obj.offsetP
console.log(obj);
console.log(stopObj);
Client: function(elem) {
this.handlers = {};
this.id = ZeroClipboard.nextId++;
this.movieId = 'ZeroClipboardMovie_' + this.
ZeroClipboard.register(this.id, this);
if (elem) this.glue(elem);
ZeroClipboard.Client.prototype = {
ready: false,
movie: null,
clipText: '',
handCursorEnabled: true,
cssEffects: true,
handlers: null,
glue: function(elem, appendElem, stylesToAdd) {
this.domElement = ZeroClipboard.$(elem);
var zIndex = 9999;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
if (typeof(appendElem) == 'string') {
if(!($('#'+ appendElem).css("position") == 'relative' || $('#'+ appendElem).css("position") == 'absolute')){
$('#'+ appendElem).css("position","relative");//如果指定的父元素不是相对和决定定位就设置父元素为相对定位
appendElem = ZeroClipboard.$(appendElem);
} else if (typeof(appendElem) == 'undefined') {
appendElem = document.getElementsByTagName('body')[0];
var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
this.div = document.createElement('div');
var style = this.div.
style.position = 'absolute';
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
style.width = '' + box.width + 'px';
style.height = '' + box.height + 'px';
style.zIndex = zI
if (typeof(stylesToAdd) == 'object') {
for (addedStyle in stylesToAdd) {
style[addedStyle] = stylesToAdd[addedStyle];
appendElem.appendChild(this.div);
this.div.innerHTML = this.getHTML(box.width, box.height);
getHTML: function(width, height) {
var html = '';
var flashvars = 'id=' + this.id + '&width=' + width + '&height=' +
if (navigator.userAgent.match(/MSIE/)) {
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '&object classid="clsid:d27cdb6e-ae6d-11cf-96b8-" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"&&param name="allowScriptAccess" value="always" /&&param name="allowFullScreen" value="false" /&&param name="movie" value="' + ZeroClipboard.moviePath + '" /&&param name="loop" value="false" /&&param name="menu" value="false" /&&param name="quality" value="best" /&&param name="bgcolor" value="#ffffff" /&&param name="flashvars" value="' + flashvars + '"/&&param name="wmode" value="transparent"/&&/object&';
html += '&embed id="' + this.movieId + '" src="' + ZeroClipboard.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" /&';
hide: function() {
if (this.div) {
this.div.style.left = '-2000px';
show: function() {
this.reposition();
destroy: function() {
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
body.removeChild(this.div);
} catch (e) {;
this.domElement = null;
this.div = null;
reposition: function(elem) {
if (elem) {
this.domElement = ZeroClipboard.$(elem);
if (!this.domElement) this.hide();
if (this.domElement && this.div) {
var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
var style = this.div.
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
setText: function(newText) {
this.clipText = newT
if (this.ready) this.movie.setText(newText);
addEventListener: function(eventName, func) {
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) this.handlers[eventName] = [];
this.handlers[eventName].push(func);
setHandCursor: function(enabled) {
this.handCursorEnabled =
if (this.ready) this.movie.setHandCursor(enabled);
setCSSEffects: function(enabled) {
this.cssEffects = !!
receiveEvent: function(eventName, args) {
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
switch (eventName) {
case 'load':
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout(function() {
self.receiveEvent('load', null);
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout(function() {
self.receiveEvent('load', null);
this.ready = true;
this.ready = true;
this.movie.setText(this.clipText);
this.movie.setHandCursor(this.handCursorEnabled);
case 'mouseover':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('hover');
if (this.recoverActive) this.domElement.addClass('active');
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
this.domElement.removeClass('hover');
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName]. idx & idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
func(this, args);
} else if ((typeof(func) == 'object') && (func.length == 2)) {
func[0][func[1]](this, args);
} else if (typeof(func) == 'string') {
window[func](this, args);
说明:父元素的设置一般情况下就是点击复制的按钮,如有其它的情况下可以修改相应的代码来适合自己的需求!
上述是在前辈已经成熟的代码的基础上做了相应的修改
此方法的要在服务器环境下才可以看到效果!
阅读(...) 评论()博客分类:
注意:此处需要使用的ZeroClipboard.js版本为1.0.7,附件中有所需js文件,如果js版本不对这个demo可能不好使
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
&TITLE& 复制demo &/TITLE&
&META NAME="Generator" CONTENT="EditPlus"&
&META NAME="Author" CONTENT=""&
&META NAME="Keywords" CONTENT=""&
&META NAME="Description" CONTENT=""&
&script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&&/script&
&script type="text/javascript"src="ZeroClipboard.js" &&/script&
&INPUT TYPE="text" NAME="" id="txt" value="复制的内容"&
&input type="button" value="复制" id="BTNcOPY_1" /&
&script type="text/javascript"&
$(function(){
$("input[id^=BTNcOPY_]").each(function(){
//ZeroClipboard.swf和ZeroClipboard.js不在相同目录下需要设置动画文件路径
//ZeroClipboard.setMoviePath("${base}/web/js/zeroclipboard-1.0.7/ZeroClipboard.swf");
var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
var obj = $(this);
var id = $(this).attr("id");
clip.glue(id);
//鼠标移上时改变按钮的样式
clip.addEventListener( "mouseOver", function(client) {
obj.css("color","#FF6600");
var txt=$("#txt").val();//设置复制内容
clip.setText(txt);
//鼠标移除时改变按钮的样式
clip.addEventListener( "mouseOut", function(client) {
obj.css("color","");
//这个是复制成功后的提示
clip.addEventListener( "complete", function(){
alert("已经复制到剪切板!");
下载次数: 251
浏览: 275910 次
来自: 北京
学习啦!谢谢
很是不错!
楼主,我安装你的方法,调不通啊。起producer的时候报错j ...
http://hi.baidu.com/django_mast ...
文字写的很好,谢谢分享。但是要调通的话 要修改一下
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'clipboard.js:最轻便的复制页面内容到剪切板的JS - 懒人的小窝

我要回帖

更多关于 clipboard.js 事件 的文章

 

随机推荐