点击按钮实现复制功能
copyText: function(message) {
var input = document.createElement("input");
input.value = message;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
document.body.removeChild(input);
}
关键的方法是 select, setSelectionRange, execCommand
select是获取焦点, document.execCommand('Copy'),execCommand命令是操纵可编辑区域的元素,参数为copy是执行选中区域的复制, ,好像这两个加起来也能达到我们想要的效果。事实上,安卓机和pc上确实没问题的,但是苹果机上却不兼容。
这时候关键的setSelectionRange开始表演了。
HTMLInputElement.setSelectionRange()方法用来设置元素当前选中的文本的开始和结束位置。记住一定是input,我用textarea也没问题。input.setSelectionRange(0, input.value.length)表示从input的第0到结尾的进行选中。
所以上面的函数连起来就是:创建一个input框,把文字赋值为input, input获取焦点,选中input中的文字,对文字进行复制,复制完成后删除input.