一. 简单用法:
// 复制URL到粘贴板
handleCopy = url => {
const textArea = document.createElement('textarea')
textArea.style.width = '0'
textArea.style.height = '0'
textArea.value = url
document.body.appendChild(textArea)
try {
textArea.select()
document.execCommand('copy')
message.success('url成功复制到剪贴板')
} catch (e) {
message.error('复制失败!')
}
document.body.removeChild(textArea)
}
二.再说一个copy-to-clipboard库,
安装:
npm i --save copy-to-clipboard
使用:
import copy from 'copy-to-clipboard';
copy('Text');
// Copy with options
copy('Text', {
debug: true,
message: 'Press #{key} to copy',
});
以下是copy-to-clipboard库实现复制的源码:
'use strict';
var deselectCurrent = require('toggle-selection');
var defaultMessage = 'Copy to clipboard: #{key}, Enter';
function format(message) {
var copyKey = (/mac os x/i.test(navigator.userAgent) ? '⌘' : 'Ctrl') + '+C';
return message.replace(/#{\s*key\s*}/g, copyKey);
}
function copy(text, options) {
var debug, message, reselectPrevious, range, selection, mark, success = false;
if (!options) { options = {}; }
debug = options.debug || false;
try {
reselectPrevious = deselectCurrent();
range = document.createRange();
selection = document.getSelection();
mark = document.createElement('span');
mark.textContent = text;
// reset user styles for span element
mark.style.all = 'unset';
// prevents scrolling to the end of the page
mark.style.position = 'fixed';
mark.style.top = 0;
mark.style.clip = 'rect(0, 0, 0, 0)';
// used to preserve spaces and line breaks
mark.style.whiteSpace = 'pre';
// do not inherit user-select (it may be `none`)
mark.style.webkitUserSelect = 'text';
mark.style.MozUserSelect = 'text';
mark.style.msUserSelect = 'text';
mark.style.userSelect = 'text';
document.body.appendChild(mark);
range.selectNode(mark);
selection.addRange(range);
var successful = document.execCommand('copy');
if (!successful) {
throw new Error('copy command was unsuccessful');
}
success = true;
} catch (err) {
debug && console.error('unable to copy using execCommand: ', err);
debug && console.warn('trying IE specific stuff');
try {
window.clipboardData.setData('text', text);
success = true;
} catch (err) {
debug && console.error('unable to copy using clipboardData: ', err);
debug && console.error('falling back to prompt');
message = format('message' in options ? options.message : defaultMessage);
window.prompt(message, text);
}
} finally {
if (selection) {
if (typeof selection.removeRange == 'function') {
selection.removeRange(range);
} else {
selection.removeAllRanges();
}
}
if (mark) {
document.body.removeChild(mark);
}
reselectPrevious();
}
return success;
}
module.exports = copy;
这里面有这么几个关方法:
-
document.createRange()
-
document.getSelection()
-
document.createElement('span')
-
document.execCommand('copy')
相信大家对select和element这样的一看就比较熟悉,那什么document.createRange()创建的是什么?document.execCommand又是什么?接下来对这两个做以下解释。
todo:其实这些都是h5的基本功能