Javascript 如何将计算值复制到剪贴板?
我有一个计算值的公式。我要将此值插入Excel工作表。为了让用户感到舒适,我想把它自动放到剪贴板上 我尝试在JS中执行我的第一步,遇到了这个(可能)非常简单的问题。但我发现的所有方法都与html输入标记的原始值相关。我从未见过任何从js中创建的值复制到剪贴板的函数Javascript 如何将计算值复制到剪贴板?,javascript,variables,clipboard,Javascript,Variables,Clipboard,我有一个计算值的公式。我要将此值插入Excel工作表。为了让用户感到舒适,我想把它自动放到剪贴板上 我尝试在JS中执行我的第一步,遇到了这个(可能)非常简单的问题。但我发现的所有方法都与html输入标记的原始值相关。我从未见过任何从js中创建的值复制到剪贴板的函数 var EEFactor = 1*1; // just a formula to calculate a value copyValue2Clipboard(EEFactor); function value2Clipboard(v
var EEFactor = 1*1; // just a formula to calculate a value
copyValue2Clipboard(EEFactor);
function value2Clipboard(value) {
// please help
}
const copyToClipboard=str=>{
const el=document.createElement('textarea');//创建一个元素
el.value=str;//将其值设置为要复制的字符串
el.setAttribute('readonly','');//使其只读以防篡改
el.style.position='绝对';
el.style.left='-9999px';//移动到屏幕外部使其不可见
document.body.appendChild(el);//将元素附加到HTML文档中
所选常数=
document.getSelection().rangeCount>0//检查之前是否选择了任何内容
?document.getSelection().getRangeAt(0)//如果找到,则存储所选内容
:false;//标记为false以知道以前不存在选择
el.select();//选择内容
document.execCommand('copy');//copy-仅在用户操作(例如单击事件)的结果下工作
document.body.removeChild(el);//删除元素
if(selected){//如果复制前存在选择
document.getSelection().removeAllRanges();//取消选择HTML文档上的所有内容
document.getSelection().addRange(已选);//恢复原始选择
}
};
像这样试试
功能copyToClipboard(str){
var el=document.createElement('textarea');
//设置值(要复制的字符串)
el.value=str;
//设置为“不可编辑”以避免聚焦并移动到视图之外
el.setAttribute('只读','');
el.style={位置:'绝对',左:'-9999px'};
文件.正文.附件(el);
//选择元素内部的文本
el.select();
//将文本复制到剪贴板
document.execCommand('copy');
//删除临时元素
文件.正文.删除文件(el);
};
var-EEFactor=1*1;
复印机(EEFactor)代码>这里有一个很好的例子
const copyToClipboard = str => {
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};