JavaScript实现点击按钮复制指定区域文本(推荐)
html5的webAPI接口可以很轻松的使用短短的几行代码就实现点击按钮复制区域文本的功能,不需要依赖flash。
代码如下:
/*创建range对象*/
constrange=document.createRange();
range.selectNode(element);//设定range包含的节点对象
/*窗口的selection对象,表示用户选择的文本*/
constselection=window.getSelection();
if(selection.rangeCount>0)selection.removeAllRanges();//将已经包含的已选择的对象清除掉
selection.addRange(range);//将要复制的区域的range对象添加到selection对象中
document.execCommand('copy');//执行copy命令,copy用户选择的文本
测试:
浏览器的版本号为我测试时使用的版本。
edge浏览器、Chrome(v54.0.2840.99m)、Firefox(v49.0.1)可用。
IE9、IE10、IE11会弹出提示询问是否将文本粘贴到剪贴板上。
IE7、IE8不支持该功能。
IOS10的Safari浏览器可用。
根据反馈,IOS9以下的Safari浏览器应该是不支持该功能的。
Demo:
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
</head>
<body>
<articleid="article">
<h4>公园一日游</h4>
<time>2016.8.15星期二</time>
<p>今天风和日丽,我和小红去了人民公园,玩了滑梯、打雪仗、划船,真是愉快的一天啊。</p>
</article>
<buttonid="copy">复制文章</button>
<textareastyle="width:500px;height:100px;"placeholder="试一试ctrl+v"></textarea>
<script>
functioncopyArticle(event){
constrange=document.createRange();
range.selectNode(document.getElementById('article'));
constselection=window.getSelection();
if(selection.rangeCount>0)selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
document.getElementById('copy').addEventListener('click',copyArticle,false);
</script>
</body>
</html>
以上所述是小编给大家介绍的JavaScript实现点击按钮复制指定区域文本,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!