[英]Javascript Copy Clipboard
我需要將文本復制到用戶剪貼板。 但是由於某種原因,這個簡單的代碼片段無法正常工作(打印錯誤)
<html>
<head>
</head>
<body>
<textarea id="clip">Test</textarea>
<script>
var ta = document.getElementById('clip');
ta.focus();
ta.select();
setTimeout(function() {
console.log(document.execCommand('copy'));
}, 1000);
</script>
</body>
</html>
我做錯什么了嗎? 有任何想法嗎?
作為用戶操作的直接結果,必須調用document.execCommand('copy')
。
例如:單擊事件處理程序。
Google開發人員職位: https : //developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=zh-CN
更新:它看起來像一個重復。 我建議您檢查有關類似主題的以下響應: https : //stackoverflow.com/a/30810322/4754887
是的,你是對的。 這工作
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id="clip" style="position: absolute; left: 100px; top: -100px;">Test</textarea>
<button id="copyButton">Copy To Clipboard</button>
<script>
document.getElementById('copyButton').addEventListener('click', function() {
var ta = document.getElementById('clip');
ta.innerHTML = "Test2";
ta.focus();
ta.select();
console.log(document.execCommand('copy'));
});
</script>
</body>
</html>
..或更簡單:
<html>
<head>
</head>
<body>
<textarea id="clip" onclick="copyToClp()">Test</textarea><!-- this executes copyToClp() function on user's click -->
<script>
var ta = document.getElementById('clip');
ta.focus();
ta.select();
function copyToClp(){
console.log(document.execCommand('copy'));
}
</script>
</body>
</html>
實際上,您應該使用Document.execCommand() (如您所做的那樣)和(非常酷的)JavaScript Selection API 。
Selection API允許您以編程方式從頁面上的任何HTML元素進行文本選擇,其工作原理與按鍵盤上的CTRL + C完全相同。 一次單擊即可快速獲取URL,長文本,SSH密鑰。
您可以嘗試這樣的事情:
var button = document.getElementById("yourButtonId");
var content = document.getElementById("yourContentElement");
button.addEventListener("click", function() {
// Define range and selection.
var range = document.createRange();
var selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
range.selectNodeContents(content);
selection.addRange(range);
// Copy to clipboard.
document.execCommand('copy');
}, false);
編輯:此方法的優點之一是您可以在剪貼板中的內容被復制后進行操作(轉義代碼,格式化數字或日期,大寫,小寫,更改HTML標記等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.