「點一下複製」是很多頁面都會用到的功能。過去只能靠 Flash 實現,現在用 HTML5 的 Selection API 短短幾行就能完成,且不需任何外部依賴。
/* 建立 range 物件 */
const range = document.createRange();
range.selectNode(element); // 設定 range 涵蓋的節點
/* 取得視窗的 selection 物件,代表使用者選取的文字 */
const selection = window.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges(); // 先清除既有選取
selection.addRange(range); // 加入要複製的範圍
document.execCommand('copy'); // 執行 copy,複製目前選取的文字
流程可以拆成三步:先用 Range 圈出目標節點,再把 Range 掛到 Selection 上讓它成為「使用者選取」,最後呼叫複製指令。中間那個 removeAllRanges() 是必要的,否則先前的選取會殘留導致範圍錯誤。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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('article'));
const selection = window.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
document.getElementById('copy').addEventListener('click', copyArticle, false);
</script>
</body>
</html>
document.execCommand('copy') 已被標示為不建議使用,但未來仍會在相容模式中保留一陣子。新專案可優先採用非同步的 navigator.clipboard.writeText(),並保留 execCommand 作為退路。writeText();若需要保留格式,則用 navigator.clipboard.write() 搭配 ClipboardItem。