代码语言:javascript复制
<input id="target" type="text" >
<button onclick="onCopyClick()">复制</button>
<script type="text/javascript">
function copyToClipboard (text) {
if (!document.createRange || !window.getSelection || !document.execCommand) {
return false;
}
const node = document.createElement('span');
node.innerText = text;
document.body.appendChild(node);
const range = document.createRange();
range.selectNode(node);
const selection = window.getSelection();
selection.empty();
selection.addRange(range);
document.execCommand('copy');
selection.empty();
range.detach();
document.body.removeChild(node);
return true;
}
function onCopyClick () {
const target = document.getElementById('target');
copyToClipboard(target.value);
}
</script>
copyToClipboard 方法用来实现复制功能,实现过程:
- 创建一个 span
- 选中span节点内容
- 使用 document.execCommand('copy')将选中内容加入剪贴板