Maison  >  Article  >  interface Web  >  JavaScript实现点击按钮复制指定区域文本

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

高洛峰
高洛峰original
2016-12-05 13:09:551823parcourir

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(&#39;article&#39;));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand(&#39;copy&#39;);
}
document.getElementById(&#39;copy&#39;).addEventListener(&#39;click&#39;, copyArticle, false);
</script>
</body>
</html>


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn