Javascript复制剪贴板
问题描述:
我需要将文本复制到用户剪贴板。但由于某种原因,这个简单的代码段不起作用(打印错误)Javascript复制剪贴板
<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')
必须作为用户操作的直接结果被调用。
例如:单击事件处理程序。
谷歌开发岗位:https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en
更新:它看起来像一个重复。我建议你结账以下类似主题的回复: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。
选择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标签等)。
可能重复[如何在JavaScript中复制到剪贴板?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) –