JavaScript 操作剪貼簿複製文字
前言:
現今要使用 JavaScript 實現 剪貼簿複製文字 非常的容易
網頁編輯器 有提供 JavaScript 的 API document.execCommand() , 可以輕易的讓我們進行 文字編輯器 的操作,其中也包含了 剪貼簿複製文字 的操作
實例:
以下為範例:
Code :
<div>
<input id ="copyInput" value ="文字1">
<button onclick='copyInput()'>複製</button>
</div>
<script>
function copyInput(){
document.getElementById('copyInput').select()
document.execCommand('copy')
}
</script>
Demo :
點選複製後,將內容加入剪貼簿
解析:
這部分一點都不難,在使用 document.execCommand() 前,先使用 select() 先選取需要操作的元素
如下:
document.getElementById('copyInput').select()
接著再直接調用 document.execCommand() 的方法就可以了