您的位置:首页 > Web前端 > JavaScript

无需Flash无需依赖任何JS库实现文本复制与剪切

2016-08-10 16:57 316 查看

无需Flash无需依赖任何JS库实现文本复制与剪切

我们在网页上放置一个复制按钮,主要用来方便用户复制链接之类的复杂文本,以往的做法是,通过JS依靠Flash,甚至借助jQuery庞大的js库来实现文本复制到剪贴板的。今天我要给大家介绍的是一款极现代的,不需要flash,不依赖任何其他js库的非常小的插件,它叫clipboard.js。

HTML

首先加载本地clipboard.js文件。

<script src="clipboard.min.js"></script> 

然后就是在body中加上要复制或剪切的文本域内容以及按钮。

<input id="foo" value="http://www.helloweba.com/demo/clipboard/"> 
<button class="btn" data-clipboard-target="#foo" aria-label="复制成功!">复制</button> 

这里,我们使用了HTML5的data-属性,用来定位复制对象目标,它指向了文本域#foo,说明复制的是#foo中的value内容,aria-label属性定义了复制成功后的信息,用来提示复制结果信息。

还有个属性data-clipboard-action,它定义当前操作是复制还是剪切,默认是复制,当data-clipboard-action="cut",这时,点击按钮将会剪切文本,跟WORD操作一样。当然,剪切操作仅适用于text和textarea。

我们也可以不需要input和textarea等元素内容作为复制对象,我们可以将要复制的内容通过ata-clipboard-text属性定义在按钮上,点击按钮就可以复制到ata-clipboard-text对应的内容。

<button class="btn" data-clipboard-text="这里是要复制的内容" aria-label="复制成功!">复制</button> 

Javascript

将以下一句代码加入到</body>前的<script>里,保存打开浏览,点击按钮即可复制。

new Clipboard('.btn'); 

当然我们可以再进一步处理,比如当复制完成后,提示复制成功信息更友好些,只要执行以下代码即可:

var clipboard = new Clipboard('.btn');  
clipboard.on('success', function(e) { 
    var msg = e.trigger.getAttribute('aria-label'); 
    alert(msg); 
 
    e.clearSelection(); 
});

由于不能上传文件,可以将一下js代码拷贝,放入文件,并命名为:clipboard.min.js
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.Clipboard=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("closest"),e=a("component-event"),f=["focus","blur"];c.bind=function(a,b,c,g,h){return-1!==f.indexOf(c)&&(h=!0),e.bind(a,c,function(c){var e=c.target||c.srcElement;c.delegateTarget=d(e,b,!0,a),c.delegateTarget&&g.call(a,c)},h)},c.unbind=function(a,b,c,d){-1!==f.indexOf(b)&&(d=!0),e.unbind(a,b,c,d)}},{closest:2,"component-event":4}],2:[function(a,b,c){var d=a("matches-selector");b.exports=function(a,b,c){for(var e=c?a:a.parentNode;e&&e!==document;){if(d(e,b))return e;e=e.parentNode}}},{"matches-selector":3}],3:[function(a,b,c){function d(a,b){if(f)return f.call(a,b);for(var c=a.parentNode.querySelectorAll(b),d=0;d<c.length;++d)if(c[d]==a)return!0;return!1}var e=Element.prototype,f=e.matchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector;b.exports=d},{}],4:[function(a,b,c){var d=window.addEventListener?"addEventListener":"attachEvent",e=window.removeEventListener?"removeEventListener":"detachEvent",f="addEventListener"!==d?"on":"";c.bind=function(a,b,c,e){return a[d](f+b,c,e||!1),c},c.unbind=function(a,b,c,d){return a[e](f+b,c,d||!1),c}},{}],5:[function(a,b,c){function d(){}d.prototype={on:function(a,b,c){var d=this.e||(this.e={});return(d[a]||(d[a]=[])).push({fn:b,ctx:c}),this},once:function(a,b,c){var d=this,e=function(){d.off(a,e),b.apply(c,arguments)};return this.on(a,e,c)},emit:function(a){var b=[].slice.call(arguments,1),c=((this.e||(this.e={}))[a]||[]).slice(),d=0,e=c.length;for(d;e>d;d++)c[d].fn.apply(c[d].ctx,b);return this},off:function(a,b){var c=this.e||(this.e={}),d=c[a],e=[];if(d&&b)for(var f=0,g=d.length;g>f;f++)d[f].fn!==b&&e.push(d[f]);return e.length?c[a]=e:delete c[a],this}},b.exports=d},{}],6:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}c.__esModule=!0;var e=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(a,d.key,d)}}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}(),f=function(){function a(b){d(this,a),this.resolveOptions(b),this.initSelection()}return a.prototype.resolveOptions=function(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=a.action,this.emitter=a.emitter,this.target=a.target,this.text=a.text,this.trigger=a.trigger,this.selectedText=""},a.prototype.initSelection=function(){if(this.text&&this.target)throw new Error('Multiple attributes declared, use either "target" or "text"');if(this.text)this.selectFake();else{if(!this.target)throw new Error('Missing required attributes, use either "target" or "text"');this.selectTarget()}},a.prototype.selectFake=function(){var a=this;this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return a.removeFake()}),this.fakeElem=document.createElement("input"),this.fakeElem.style.position="absolute",this.fakeElem.style.left="-9999px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.selectedText=this.text,document.body.appendChild(this.fakeElem),this.fakeElem.select(),this.copyText()},a.prototype.removeFake=function(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),t
4000
his.fakeElem=null)},a.prototype.selectTarget=function(){if("INPUT"===this.target.nodeName||"TEXTAREA"===this.target.nodeName)this.target.select(),this.selectedText=this.target.value;else{var a=document.createRange(),b=window.getSelection();a.selectNodeContents(this.target),b.addRange(a),this.selectedText=b.toString()}this.copyText()},a.prototype.copyText=function(){var a=void 0;try{a=document.execCommand(this.action)}catch(b){a=!1}this.handleResult(a)},a.prototype.handleResult=function(a){a?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},a.prototype.clearSelection=function(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},e(a,[{key:"action",set:function(){var a=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=a,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(a){if(void 0!==a){if(!a||"object"!=typeof a||1!==a.nodeType)throw new Error('Invalid "target" value, use a valid Element');this._target=a}},get:function(){return this._target}}]),a}();c["default"]=f,b.exports=c["default"]},{}],7:[function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function f(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}c.__esModule=!0;var g=a("./clipboard-action"),h=d(g),i=a("delegate-events"),j=d(i),k=a("tiny-emitter"),l=d(k),m="data-clipboard-",n=function(a){function b(c,d){e(this,b),a.call(this),this.resolveOptions(d),this.delegateClick(c)}return f(b,a),b.prototype.resolveOptions=function(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof a.action?a.action:this.setAction,this.target="function"==typeof a.target?a.target:this.setTarget,this.text="function"==typeof a.text?a.text:this.setText},b.prototype.delegateClick=function(a){var b=this;j["default"].bind(document.body,a,"click",function(a){return b.initialize(a)})},b.prototype.initialize=function(a){this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new h["default"]({action:this.action(a.delegateTarget),target:this.target(a.delegateTarget),text:this.text(a.delegateTarget),trigger:a.delegateTarget,emitter:this})},b.prototype.setAction=function(a){return a.hasAttribute(m+"action")?a.getAttribute(m+"action"):void 0},b.prototype.setTarget=function(a){if(a.hasAttribute(m+"target")){var b=a.getAttribute(m+"target");return document.querySelector(b)}},b.prototype.setText=function(a){return a.hasAttribute(m+"text")?a.getAttribute(m+"text"):void 0},b}(l["default"]);c["default"]=n,b.exports=c["default"]},{"./clipboard-action":6,"delegate-events":1,"tiny-emitter":5}]},{},[7])(7)});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js flash 无需Flash J