JavaScript实现复制或剪切内容到剪贴板功能的方法
项目中需要实现一个点击按钮复制链接的功能,网上看到的几款插件,ZeroClipboard是通过flash实现的复制功能,随着越来越多的提议废除flash,能不能通过JS来实现复制剪切呢,今天分享一个兼容IE7浏览器复制的插件给大家,支持使用javascript实现复制、剪切和粘贴。
方法。
复制
varcopy=newclipBoard(document.getElementById('data'),{
beforeCopy:function(){
},
copy:function(){
returndocument.getElementById('data').value;
},
afterCopy:function(){
}
});
复制将自动被调用,如果你想要自己调用:
varcopy=newclipBoard(document.getElementById('data'));
copy.copyd();
document.getElementById('data'):要获取的对象,你也可以使用jQuery$('#data')
剪切
基本上与复制的实现方法相同:
varcut=newclipBoard(document.getElementById('data'),{
beforeCut:function(){
},
cut:function(){
returndocument.getElementById('data').value;
},
afterCut:function(){
}
});
或者
varcut=newclipBoard(document.getElementById('data'));
cut.cut();
paste
varpaste=newclipBoard(document.getElementById('data'),{
beforePaste:function(){
},
paste:function(){
returndocument.getElementById('data').value;
},
afterPaste:function(){
}
});
或者
varpaste=newclipBoard(document.getElementById('data'));
paste.paste();
完整代码:
(function(name,fun){
if(typeofmodule!=='undefined'&&module.exports){
module.exports=fun();
}elseif(typeofdefine==='function'&&define.amd){
define(fun);
}else{
this[name]=fun();
}
})('clipBoard',function(){
"usestrict";
functionclipBoard(tar,options){
this.options=options||{};
this.tar=tar[0]||tar;
//ifoptionscontaincopy,copywillbeappliedsoon
if(this.options.copy){
this.copyd();
}
if(this.options.cut){
this.cut();
}
if(this.options.paste){
this.paste();
}
}
clipBoard.prototype.copyd=function(value){
//beforethecopyitwillbecalled,youcancheckthevalueormodifythevalue
if(this.options.beforeCopy){
this.options.beforeCopy();
}
//iftheoptionssetcopyfunction,thevaluewillbeset.thengettheparamervalue.
//aboveall,ifthevalueisnull,thenwillbesetthetarofvalue
value=value||this.tar.value||this.tar.innerText;
if(this.options.copy){
value=this.options.copy();
}
//formodernbrowser
if(document.execCommand){
varelement=document.createElement('SPAN');
element.textContent=value;
document.body.appendChild(element);
if(document.selection){
varrange=document.body.createTextRange();
range.moveToElementText(element);
range.select();
}elseif(window.getSelection){
varrange=document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
document.execCommand('copy');
element.remove?element.remove():element.removeNode(true);
}
//forie
if(window.clipboardData){
window.clipboardData.setData('text',value);
}
//aftercopy
if(this.options.afterCopy){
this.options.afterCopy();
}
};