不知道为什么今天这对我来说如此困难,但由于某种原因,我似乎无法将当前 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 is not a function
所以我不是 100% 确定最好的方法是什么。同样,不使用 jQuery(或任何其他 JS 库)并且不使用某种隐藏的文本字段。