不知道为什么今天这对我来说如此困难,但出于某种原因,我似乎无法将当前 URL 复制到剪贴板。总的来说,我正在寻找一种无需创建一些隐藏文本元素的方法。
这是我目前正在尝试的:
var shareBtn = document.querySelector(".share-button");
shareBtn.addEventListener('click', function(event) {
var cpLink = window.location.href;
cpLink.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
event.preventDefault;
});
当我尝试使用 .select()
执行此操作时,出现此错误:
t.select 不是函数
所以我不是 100% 确定最好的方法是什么。同样,不使用 jQuery(或任何其他 JS 库)并且不使用某种隐藏的文本字段。
最佳答案
您可以创建一个临时 DOM 元素来保存 URL
不幸的是,没有用于剪贴板操作的标准 API,因此我们只能使用 HTML input
元素来满足我们的需求。这个想法是创建一个输入,将其值设置为当前文档的 URL,选择其内容并执行 copy
。
然后我们清理困惑,而不是将输入设置为隐藏并污染 DOM。
var dummy = document.createElement('input'),
text = window.location.href;
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
关于javascript - 将当前 URL 复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49618618/