Skip to content

Instantly share code, notes, and snippets.

@magicianShiro
Last active October 25, 2019 03:30
Show Gist options
  • Save magicianShiro/b046dee083d0ff60b419a4a8542e3cb5 to your computer and use it in GitHub Desktop.
Save magicianShiro/b046dee083d0ff60b419a4a8542e3cb5 to your computer and use it in GitHub Desktop.
复制文本
export default (function clipboard(document) {
let textArea;
// 创建文本元素
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.setAttribute('readonly', true);
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
}
function copyToClipboard() {
return new Promise((resolve, reject) => {
// document.execCommand('selectAll')解决ios下select选取不到文本的问题
if (document.execCommand('selectAll') && document.execCommand('Copy')) {
window.getSelection().removeAllRanges();
resolve();
} else {
reject();
}
document.body.removeChild(textArea);
});
}
function copy(text) {
createTextArea(text);
return copyToClipboard();
}
return copy;
}(document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment