您好,欢迎访问一九零五行业门户网

JavaScript实现点击按钮复制指定区域文本

html5的webapi接口可以很轻松的使用短短的几行代码就实现点击按钮复制区域文本的功能,不需要依赖flash。
代码如下:
/* 创建range对象 */ const range = document.createrange(); range.selectnode(element); // 设定range包含的节点对象 /* 窗口的selection对象,表示用户选择的文本 */ const selection = window.getselection(); if(selection.rangecount > 0) selection.removeallranges(); // 将已经包含的已选择的对象清除掉 selection.addrange(range); // 将要复制的区域的range对象添加到selection对象中 document.execcommand('copy'); // 执行copy命令,copy用户选择的文本
测试:
浏览器的版本号为我测试时使用的版本。
edge浏览器、chrome(v54.0.2840.99 m)、firefox(v49.0.1)可用。
ie9、ie10、ie11会弹出提示询问是否将文本粘贴到剪贴板上。
ie7、ie8不支持该功能。
ios10的safari浏览器可用。
根据反馈,ios9以下的safari浏览器应该是不支持该功能的。
demo:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <article id="article"> <h4>公园一日游</h4> <time>2016.8.15 星期二</time> <p>今天风和日丽,我和小红去了人民公园,玩了滑梯、打雪仗、划船,真是愉快的一天啊。</p> </article> <button id="copy">复制文章</button> <textarea style="width: 500px;height: 100px;" placeholder="试一试ctrl + v"></textarea> <script> function copyarticle(event){ const range = document.createrange(); range.selectnode(document.getelementbyid('article')); const selection = window.getselection(); if(selection.rangecount > 0) selection.removeallranges(); selection.addrange(range); document.execcommand('copy'); } document.getelementbyid('copy').addeventlistener('click', copyarticle, false); </script> </body> </html>
其它类似信息

推荐信息