Home  >  Article  >  Web Front-end  >  JavaScript implements clicking a button to copy text in a specified area

JavaScript implements clicking a button to copy text in a specified area

高洛峰
高洛峰Original
2016-12-05 13:09:551824browse

The webAPI interface of html5 can easily use just a few lines of code to realize the function of clicking a button to copy area text, without relying on flash.

The code is as follows:

/* 创建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用户选择的文本


Test:

The version number of the browser is the version I used when testing.

edge browser, Chrome (v54.0.2840.99 m), Firefox (v49.0.1) are available.

IE9, IE10, and IE11 will pop up a prompt asking whether to paste the text to the clipboard.

IE7 and IE8 do not support this function.

Safari browser for IOS10 is available.

According to feedback, Safari browsers below IOS9 should not support this feature.

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>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn