我试图为用户提供一种在他/她进入页面时自动复制文本的方法。 我可以使用输入和按钮使其工作,如下所示:
<input type="text" id="text-field" value="Some text">
<button onclick="copyToClipboard()"> Copy </button>
这个 js 函数:
const copyToClipboard = str => {
$('#text-field').select();
try {
if (!document.execCommand('copy')) {
throw false;
}
alert('Copied');
} catch (error) {
alert('An error has occurred!');
}
};
当我单击按钮时,文本将被复制。
问题是我想在页面加载时执行此操作。所以,我尝试写这样的东西:
$(function() {
copyToClipboard();
});
但它显示“已发生!”
有什么办法可以实现这个功能吗?
最佳答案
这是预期的行为。
https://www.w3.org/TR/clipboard-apis/#integration-with-rich-text-editing
Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.
关于javascript - 页面准备好后将文本复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875007/