我有以下代码,用于chrome插件的js将某些数据从某个网页复制到剪贴板(稍后我将编写代码从网页获取数据)。
// 1. Create the button
var testButton = document.createElement("button");
testButton.innerHTML = "Copy";
// 2. Append somewhere
var btnPos = document.getElementsByClassName("menu-userdetails")[0];
btnPos.appendChild(testButton);
// 3. Add event handler
testButton.addEventListener ("click", copyToClipboard);
function copyToClipboard() {
var textArea = document.createElement("textarea");
textArea.value = "test copying";
btnPos.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
在此代码中,我必须在复制之前将文本区域附加到网页(单击按钮后)。但我不想显示文本区域,我只想复制文本区域内的数据而不显示文本区域。
最佳答案
textArea.style.height = "0px";
textArea.style.width = "0px";
textArea.style.opacity = "0";
添加此代码会隐藏文本区域。
但是更好的解决方案已经在我的代码中,我只是犯了一个小错误。 我写的
document.body.removeChild(textArea);
虽然实际上我必须写
btnPos.removeChild(textArea);
这会在复制后删除文本区域,而且速度非常快,您甚至看不到文本区域的出现和消失。
关于javascript - 复制到剪贴板而不附加文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821899/