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>

 

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