问题
I'm trying to copy string variable to clipboard.
I could find a lot of examples that copy the values from < input > or < p > tags, But my problem in case I make a changes on variable then I want to copy it such as this example
var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");
回答1:
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>
Hope it helps!
回答2:
I got the solution
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);
来源:https://stackoverflow.com/questions/48370896/how-to-copy-the-value-of-variable-in-javascript