使用JS实现复制功能

2017-02-16  本文已影响0人  shirleyyu001
原理:

1、document.execCommand可作用于以下类型的元素上:

  • input
  • textarea
  • contenteditable属性为"true"的元素
  • designMode属性为"on"的iframe元素

2、使用select()方法选中需要复制的文本。

由于select()方法只能作用于文本框,所以用这个方法来实现复制功能有很大的局限性。

若要突破限制,则需要使用其它方式(比如手动)选中想要复制的文本。
简单实现:
//html
<textarea style="width: 200px;height: 200px;" id="edit" autofocus></textarea>
<button id="copy">copy</button>

//js
document.getElementById('copy').addEventListener('click',function(e){
    var dom=document.getElementById('edit');
    dom.select();  //若是使用其它方式选中要复制的文本,则此处可去掉
    document.execCommand('copy',false,null);  //这一步是关键,会选中当前窗口中被选中的文本。若是写成:frames['frame'].document.execCommand('copy',false,null),则会复制name=frame中被选中的文本
})
document.getElementById ('edit').addEventListener('copy',function(e){
    console.log(e);
})
document.execCommand()兼容性
compatibility.png
上一篇下一篇

猜你喜欢

热点阅读