如今因隐私保护,因此不少新版本的浏览器都再也不支持clipbaordData访问粘贴板,网络中利用clipbaordData来解决设置copy文本的方法已经不可用了。本文将介绍如何实现一个自定义设置copy文本。copy非文本内容请参考clipboard.js。javascript
参考自clipboard.js的源码。
思路是建立一个不可见的textarea,将要复制的内容赋值给textarea.value。而后textarea.select(),达到选中的效果;
最后执行document.execCommand('copy'),copy完成。java
支持IE9+,chrome,FF等浏览器。用typescript写的须要编译后使用。(仅供参考)git
export Class Clipboard { private ids: Array = []; private handler: any = {}; private options: any = {}; private elm: Element = null; construtor(id = '', opt = {}){ this.options = opt; this.Init(id); } // 销毁对象 public Destroy() { // 删除 textarea const parent = this.elm.parentElement; parent.removeChild(this.elm); // 解绑click事件 const ids = this.ids; const len = ids.length; const fn = this.handler.fn; for(let i = 0; i < len; i++){ ids[i].removeEventListener('click', fn); } this.ids = null; } public setCopyContent(content) { const elm = this.elm; elm.value = content; elm.select(); // 设置当前光标选择稳步的位置--不使用也可正常复制 // elm.setSelectionRange(0, content.length); document.execCommand('copy'); } // 获取id相关的element并绑定click事件执行setCopyConetent private Init(id) { const self = this; const ids = this.ids = document.querySelectorAll(id); this.elm = this.CreateTextArea(); const len = ids.length; this.handler = { fn: (ev) => { return this.ClickHandler(ev); } }; for(let i = 0; i < len; i++) { ids[i].addEventListener('click', this.handler.fn); } } private ClickHandler(ev) { let text = ''; const opt = this.options; if (typeof opt.text) { text = opt.text(ev); } else { text = opt.text; } this.setCopyContent(text); } // 建立不可见的textarea private CreateTextArea() { const el = document.createElement('textarea'); el.style = { width: '0px', height: '0px', position: 'fixed', top: '-10px' }; el.setAttribute('readonly', ''); document.body.appendChild(el); return el; } }
const clip = new Clipboard(); clip.setClipContent('test copy'); // or const clip = new Clipboard('.btn', { // text: 'test copy' text: function(ev){ return ev.target.getAttribute('data-copy') } });