js原生实现鼠标点击元素复制指定的内容

 js原生实现鼠标点击元素复制指定的内容:直接看代码吧:

<!DOCTYPE html>
<html lang="en">
<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){
	debugger;
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');
selection.removeAllRanges()////删除鼠标点击选中文字的丑陋的背景效果  
}
document.getElementById('copy').addEventListener('click', copyArticle, false);
// /* 创建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用户选择的文本
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章