如何在javascript中复制变量的值

时间:2018-01-21 19:36:49

标签: javascript copy clipboard

我试图将字符串变量复制到剪贴板。

我可以找到很多复制<值的示例。输入>或者< p>标签,但我的问题,如果我对变量进行更改,然后我想复制它,如此示例

var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");

2 个答案:

答案 0 :(得分:0)

我得到了解决方案

var dummy = document.createElement("input");
//dummy.style.display = 'none'
document.body.appendChild(dummy);
//$(dummy).css('display','none');
dummy.setAttribute("id", "dummy_id");
//dummy.setAttribute('value', document.URL + '; ' + document.title)
dummy.setAttribute('value', textX) //TEXTX is the value of variable
//document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);

答案 1 :(得分:0)



var getNum1 = function() {
  return 1;
};

var getNum2 = function() {
  return 2;
};

var num1 = getNum1();
var num2 = getNum2();
var result = ((num1 * num2) / 3) - 1;

var executeCopy = function() {
  var copyhelper = document.createElement("input");
  copyhelper.className = 'copyhelper'
  document.body.appendChild(copyhelper);
  copyhelper.value = result;
  copyhelper.select();
  document.execCommand("copy");
  document.body.removeChild(copyhelper);
};

document.getElementById('mybutton').addEventListener('click', function() {
  executeCopy();

  alert("your results has been copied");
});

.copyhelper {
  position: absolute;
}

<button id='mybutton'>Copy to clipboard</button>
&#13;
&#13;
&#13;

希望有所帮助!